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() { ... }
Cleanup:
public static readonly List<int> MyList = GetMyList();
//Returns the list
private static List<int> GetMyList() { ... }
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>
?
A readonly field can be initialized either at the time of declaration or within the constructor of the same class. Therefore, readonly fields can be used for run-time constants. Explicitly, you can specify a readonly field as static since like constant by default it is not static.
The keyword readonly has a value that may be changed or assigned at runtime, but only through the non-static constructor. There isn't even a method or static method.
A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime.
Difference between const and readonlyconst variables can declared in methods ,while readonly fields cannot be declared in methods. const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
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.
The reason is that when you write
() =>
{
...
return list;
};
You're actually declaring a delegate - a function that returns List<int>
, but you're not actually invoking that function, and therefore this evaluates to Func<List<int>>
and not to List<int>
.
I'm not quite sure why you're trying to remove your static constructor though. Static constructors have their uses, and in some cases even make the code cleaner and more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With