Question

I am trying to create a static variable inside class like below,

public class ClassEnLanguage
{
  public static Dictionary<string, string> dictionary = new Dictionary<string, string>();
}

this is no problem work fine even I can access this from other class, now I want to add values into dictionary object without using any method. like,

public class ClassEnLanguage
{
 public static Dictionary<string, string> dictionary = new Dictionary<string, string>();
    dictionary.Add("somekey1","someValue1");
    dictionary.Add("somekey2","someValue2");
}

Like in Java we can do like that,

public class ClassLanguageEn {
     public static HashMap labels = new HashMap();
        static {        
            labels.put("somekey1","someValue1");
            labels.put("somekey2","someValue2");
               }
}

and we can access this variable using ClassLanguageEn.labels (Classname.VariableName).

Now my question is will it possible to do.

Was it helpful?

Solution

You can use a type initializer, or static constructor, like this:

public class ClassEnLanguage
{
    public static Dictionary<string, string> dictionary = new Dictionary<string, string>();
    static ClassEnLanguage()
    {
        dictionary.Add("somekey1","someValue1");
        dictionary.Add("somekey2","someValue2");
    }
}

Note that you can also use a dictionary initializer like this:

public class ClassEnLanguage
{
    public static Dictionary<string, string> dictionary = new Dictionary<string, string>
        {
            { "somekey1", "someValue1" },
            { "somekey2", "someValue2" }
        };
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top