c# - public static readonly field vs getter for a lookup list -


i'm choosing between 2 implementations lookup (readonly) list of strings.

with getter:

public static list<string> mylist { { return mylist; } } private static readonly list<string> mylist = new list<string> {     "item 1", "item 2", "item 3" }; 

or simply:

public static readonly list<string> mylist = new list<string> {     "item 1", "item 2", "item 3" }; 

i go second 1 simplicity, reading code looks second implementation create new list every time, whereas in first implementation there's no such recurring overhead.

is right way think it? or there better implementations trying achieve?

thanks!

personally i'd recommend using properties because they're more flexible. example implement lazy loading of collection behind property, can't field.

however, there's much bigger problem code. read fields , read properties ensure reference mylist cannot reassigned list. it's important realize neither of these options makes list read only.

in both cases there's nothing stopping other code calling:

myclass.mylist.clear(); myclass.mylist.add("foo"); 

i'd strongly recommend this:

public static ilist<string> mylist { { return mylist; } } private static readonly readonlycollection<string> mylist =      new readonlycollection<string>(new[]     {         "item 1", "item 2", "item 3"     }); 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -