vb.net - Why doesn't static works as expected in this lazy loading code? -


the code simple. lazy loads dictionary. if dictionary nothing fills dictionary.

however, when go through program code inside if _countrydictionary nothing then called several times. wonder went wrong?

           static _countrydictionary generic.dictionary(of string, string)            if _countrydictionary nothing             _countrydictionary = new generic.dictionary(of string, string)              dim listofcountries = filetocol(countrycodesfilename)              each var in listofcountries                 dim ar = var.split({"*"}, system.stringsplitoptions.none).tolist()                 _countrydictionary.add(lcase(ar(0)), ucase(ar(1)))             next             _countrydictionary.add("delete", "de")             _countrydictionary.add("default", "df")             _countrydictionary.add("pakinmay", "py")          end if          return _countrydictionary(country)     end 

enter image description here here screenshot of debugging. see it's still nothing. static keywords work differently on method in vb.net?

update: based on answer, seems static variable here different different instance of class. thought word static means variable not in heap in stack or in code portion. guess wrong.

as @mark pointed in comment , documents, static keyword define variable shared between different calls procedure static variable defined (getter in case)

public class test      public readonly property value integer                     static someconstant integer = 0             someconstant += 1             return someconstant         end     end property  end class  sub main()    dim test1 new test()   console.writeline(test1 .value) 'print 1   console.writeline(test1 .value) 'print 2    dim new test()   console.writeline(another.value) 'print 1   console.writeline(another.value) 'print 2  end sub 

so in case getter countrycode executed different instances of class.

if want share instance between instances of class, create static member using keyword shared

public class yourclass      private shared readonly countrydictionary dictionary(of string, string)      public readonly property countrycode string                     return yourclass.countrydictionary("country")         end     end property  end class 

then use in same way have used _countrydictionary variable


Comments