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:
- The
propertySetter
delegate is unassigned in theMain()
, so why is it allowed to be used? - When the arguments are passed in the
propertySetter(sm, "Johnny Bravo");
what directs it to go to the assigner Dictionary? - 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 thepropertySetter(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.