Alex Rivera | Logout

Initializing a static field vs. returning a value in static property get?

Asked 2011-03-18T15:17:52.343
36

A) In the following code, will the method DataTools.LoadSearchList() only be called once, or every time the property is being accessed?

public static IEnumerable<string> SearchWordList
{
    get
    {
        return DataTools.LoadSearchList();
    }
}

B) Is there any difference to this?

public static IEnumerable<string> SearchWordList = DataTools.LoadSearchList();
Edit
Report

1 Answer

19

In the first case the method will be called every time the property is accessed. When it's set as a field, it will be run exactly once - when the type it initialized - whether or not it's ever accessed.

If you want a lazily-initialized value, I'd recommend Lazy<T> from .NET 4.

answered 2011-03-18T15:19:51.787

Your Answer