Reputation: 23
I'm new to C# scripting.
I'm reading some code , and inside a class method there is a call to a function to add to a Dictionary instance named Listeners like this:
public class ......
{
private Dictionary<string, List<Component>> Listeners =
new Dictionary<string, List<Component>>();
public void AddListener(Component Listener, string NotificationName)
{
// Add listener to dictionary
if (!Listeners.ContainsKey(NotificationName))
Listeners.Add (NotificationName, new List<Component>());
// Add object to listener list for this notification
Listeners[NotificationName].Add(Listener);
}
}
Now, it seems the call to Listeners.Add has a constructor call
new List<Component>()
as an argument.
Am I getting it right ?
Upvotes: 1
Views: 357
Reputation: 660048
Now , it seems the call to
Listeners.Add
...
You mean not the call to Listeners[NotificationName].Add
I assume.
... has a constructor call
new List<Component>()
as an argument. Am I getting it right ?
Yes, the call has two arguments. The first argument is a formal parameter of the current method, and the second argument is an object creation expression. The values of those arguments at runtime will be a reference to a string and a reference to a newly created object.
The order of operations here is, first the receiver is evaluated, then those argument values will be generated, and then the Add
method will be invoked with those values copied into its formal parameters and the receiver value used as this
.
The meaning of the code is "I have a map from names to lists of stuff; if this map has no mapping for a particular name, create a mapping from the name to an empty list of stuff". The second Add
call then adds a single element to that list of stuff.
From a comment on another answer:
I cannot get my hands on the instance reference outside that function call
Well, you do get your hands on it, on the very next line, by reading it right back out of the map again. But without a device that allows you to obtain that value by evaluating another expression, as you do here, you are correct. That expression simply produces a value; it does not associate any name with it that you can then use later on. If you'd wanted to do that then you'd want to create a local variable.
Upvotes: 4
Reputation: 354506
Nope, the call gets a new instance of a List<Component>
as argument.
Unlike methods, constructors cannot be really referenced. While you can store a method reference in a delegate and later call it, you cannot do the same with constructors. Although that is more or less moot here, because
Listeners.Add (NotificationName, new List<Component>());
means roughly the following:
var param1 = NotificationName;
var param2 = new List<Component>();
Listeners.Add(param1, param2);
As you can see, a new list is created, and that new list is passed to the Add
method.
Upvotes: 0