Search code examples
c#delegatesunassigned-variable

C# How does code involving delegates work?


This is a prototype of some of my code in the project that I've gotten from here, but I'm struggling to understand why it works the way it does. Here's the code.

    static void Main(string[] args)
    {
        SomeClass sm = new SomeClass();
        var assigner = new Dictionary<string, Action<SomeClass, string>>
        {
            ["TargetText"] = (someClass, value) => someClass.Name = value,
        };

        for (int i = 0; i < 10; i++)
        {
            Action<SomeClass, string> propertySetter;
            if (!assigner.TryGetValue("TargetText", out propertySetter))
            {
                continue;
            }
            else
                propertySetter(sm, "Johnny Bravo");
        }
        Console.WriteLine(sm); // output Johnny Bravo ????
    }
}
public class SomeClass
{
    string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    public override string ToString()
    {
        return $"{Name}";
    }
}

Questions:

  1. The propertySetter delegate is unassigned in the Main(), so why is it allowed to be used?
  2. When the arguments are passed in the propertySetter(sm, "Johnny Bravo"); what directs it to go to the assigner Dictionary?
  3. When it does get to the dictionary, how does it know which lambda expression to execute (provided there are multiple) as I don't see something like "TargetText" being passed along with the propertySetter(sm, "Johnny Bravo");

Those are the only questions I have right now about this, I'll update this post if I think of anything else.


Solution

  • The propertySetter delegate is unassigned in the Main(), so why is it allowed to be used?

    Because you are passing it as an out argument on the if statement which guarantees that it will be initialized to a value.

    When the arguments are passed in the propertySetter(sm, "Johnny Bravo"); what directs it to go to the assigner Dictionary?

    You have an action delegate in the dictionary associated with the key TargetText which you are looking up in:

    assigner.TryGetValue("TargetText", out propertySetter)
    

    So that delegate is assigned to propertySetter and it takes an instance of SomeClass and sets its Name property to a given value. After that point all the delegate needs is an instance of the class and a value, which you are passing in:

    propertySetter(sm, "Johnny Bravo");