c# - Initialize list with default values -


i want have class, stores "allowed languages" in list. code party should able modify list. on first usage, list should "initialized" default values.

i have following class:

public class apilanguages {     public static list<string> allowedlanguages { get; set; }      public apilanguages()     {         allowedlanguages.add("de");         //allowedlanguages.add("en");         //allowedlanguages.add("es");         //allowedlanguages.add("fr");         //allowedlanguages.add("it");     } } 

when access class in code with

foreach (var language in apilanguages.allowedlanguages) {       // here... } 

the apilanguages.allowedlanguages null. expect 1 entry ("de"). doing wrong here?

public apilanguages() instance constructor. runs (and every time) when create new instance of apilanguages (via new apilanguages()). it's purpose initialize instance variables, not static ones. shouldn't initialize static properties or fields in instance constructor.

you need use static constructor initialize static list this:

public class apilanguages {     public static list<string> allowedlanguages { get; set; }      static apilanguages()     {         allowedlanguages = new list<string>();         allowedlanguages.add("de");         //...     } } 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -