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

In your first example, LoadSearchList() will be called each time the property is accessed.

In the second, LoadSearchList() will only be called once (but it will be called whether you use it or not since it is now a field rather than a property).

A better option might be:

private static IEnumerable<string> _searchWordList;

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

Or if you’re using .NET 4.0 and want something thread-safe you can use Lazy<T>, as Jon Skeet mentioned (I think the syntax should be correct, but don’t hold me to it):

private static Lazy<IEnumerable<string>> _searchWordList =
    new Lazy<IEnumerable<string>>(() => DataTools.LoadSearchList());

public static IEnumerable<string> SearchWordList
{
    get { return _searchWordList.Value; }
}

Leave a Comment