How to initialize a static readonly variable using an anonymous method?

anonymous-function, c#, delegates, static, static-members

Solution

This looks a little weird, but try this:

public static readonly List<int> MyList = new Func<List<int>>(
() =>
{
    // Create your list here
    return new List<int>();
})();

The trick is creating a new `Func<List<int>>` and invoking it.

Problem

I'm trying to clean up my code for initializing static readonly variables. Original: ``` public static readonly List<int> MyList; //Initialize MyList in the static constructor static MyObject() { ... } ``` I decided to clean it up because CodeAnalysis said I should not use the static constructor (CA1810). Cleanup: ``` public static readonly List<int> MyList = GetMyList(); //Returns the list private static List<int> GetMyList() { ... } ``` I didn't really like the additional method, so I figured I'd try to get it to be all inline, but it won't work. I'm not sure what I'm doing wrong here... ``` public static readonly List<int> MyList = () => { ... return list; }; ``` I attempted to take the code within the `GetMyList()` method and place it in an anonymous delegate to return the list to assign, but it says I'm attempting to convert a `delegate` into a `List<int>`?

Original source