The following code creates a dictionary with Action
s.
class Test
{
private Dictionary<string, Action> ActionLookup = new();
public Test()
{
ActionLookup.Add("key", SampleAction);
}
protected virtual void SampleAction()
{
// Do something useful here...
}
}
That code works. However, the following version gives me a compile error.
class Test
{
private Dictionary<string, Action> ActionLookup = new()
{
["key"] = SampleAction // ERROR CS0236
};
protected virtual void SampleAction()
{
// Do something useful here...
}
}
Error CS0236 A field initializer cannot reference the non-static field, method, or property
Why can't I add SampleAction
to my dictionary using a collection initializer when it's perfectly valid to add it manually?
I know I can workaround it using something like the following, but why is this necessary?
class Test
{
private Dictionary<string, Action<MyClass>> ActionLookup = new()
{
["key"] = o => o.SampleAction()
};
protected virtual void SampleAction()
{
// Do something useful here...
}
}
Note: It's not an option to make SampleAction
static because I need it to be virtual
.