Why is the following C# not legal? Does there exist a proper workaround?
public class Base
{
public Base(Func<double> func) { }
}
public class Derived : Base
{
public Derived() : base(() => Method()) <-- compiler: Cannot access non-static method 'Method' in static context
{
}
public double Method() { return 1.0; }
}
It’s effectively referring to “this” within the arguments to the base constructor, which you can’t do.
If your delegate really doesn’t need access to
this(which your sample doesn’t) you can just make it static. You could also use a method group conversion to make it simpler:If you do need to use “this”, you could:
Make it a static method which takes an appropriate instance, e.g.