monogate monogate - 2 months ago 5
C# Question

C# How does Dictionary works when we initialize a class within as a value?

Assuming I have the following code:

public static Dictionary<string, ViewModelBase> LoadDictionary()
{
Dictionary<string, ViewModelBase> tempDictionary = new Dictionary<string, ViewModelBase>();
tempDictionary.Add("LoginView", new LoginViewModel());
tempDictionary.Add("SignUpView", new SignUpViewModel());
tempDictionary.Add("ContactListView", new ContactListViewModel());
return tempDictionary;
}


I refer to this line:

Dictionary<string, ViewModelBase> tempDictionary = new Dictionary<string, ViewModelBase>();


Does the compiler first creates a constructor (parameterless ctor) and only then add my KeyValuePairs?

if so, how will my parameter ctor would look like? (of the LoadDictionary)

and the most important question relevant to this post:

When I add my KeyValuePairs, are the Values also instantiated? or simply wait to be called and then are instantiated?

I mean to:

new LoginViewModel()

new SignUpViewModel()

new ContactListViewModel()

EDIT:

I Simply wanna know if this code:

tempDictionary.Add("LoginView", new LoginViewModel());

would be executed and call the LoginViewModel constructor even if I did not call the "LoginView" key in any other part of my program.

Thanks for the feedbacks, I've changed my title and my content.

Answer

Does the compiler first creates a constructor (parameterless ctor) and only then add my KeyValuePairs?

The compiler doesn't have to create anything. Dictionary<> has a parameterless constructor, which you're calling here:

new Dictionary<string, ViewModelBase>();

You're simply invoking the constructor, passing no parameters, and getting back an instance of a Dictionary<string, ViewModelBase>.

When I add my KeyValuePairs, are the Values also instantiated?

They're instantiated, because you're instantiating them:

new LoginViewModel()

Like any other constructor, this creates a new instance of the class.


Note that none of the code you're showing really has anything to do with class initializers. An initializer for a collection type (like a Dictionary<>) might look something like this:

Dictionary<string, ViewModelBase> tempDictionary = new Dictionary<string, ViewModelBase>() { 
     {"LoginView", new LoginViewModel()},
     {"SignUpView", new SignUpViewModel()}, 
     {"ContactListView", new ContactListViewModel()} 
 }

Which is compiled to essentially the equivalent of what you have:

Dictionary<string, ViewModelBase> tempDictionary = new Dictionary<string, ViewModelBase>();
tempDictionary.Add("LoginView", new LoginViewModel());
tempDictionary.Add("SignUpView", new SignUpViewModel());
tempDictionary.Add("ContactListView", new ContactListViewModel());

It's not entirely clear where your confusion is on the subject, but essentially all any of this code does is create instances of objects.

Comments