I have this:
public class Demo {
private IService _service;
Action<Guid> action = v => _service.CallServiceWithParameter(v);
}
I get error:
Cannot access non-static field '_service' in static context
huh? Where is the static context and why is a lambda forced to be static? the lambda itself is not static...
Field initializers are static statements that are evaluated before the constructor is executed, which is why they can only access other static items.
You can see this if you try to replace the initializer with a method call; it will only compile if you make that method static.
Here is a runnable Demo fiddle: https://dotnetfiddle.net/IVtMHJ
Code from the fiddle:
Output:
If you move the
CreateActioncall into the constructor then you can make it non-static:Output (from fiddle):