Thanks to the answers to this question I am able to override a virtual method in C# when I extend a class into a kind of anonymous type.
But is it possible to refer to a class variable or property of the ancestor class?
Here is a simplified version of my C# code:
public class MyAsyncBackgroundJob<TExecuteArgs> {
public Func<TExecuteArgs, Task> ExecutePropAsync { get; set; }
protected int _myVariable = 1; // just an example
public int MyProp { get; set; } = 2; // just an example
public MyAsyncBackgroundJob() {
}
public override Task ExecuteAsync(TExecuteArgs args) {
return ExecutePropAsync(args);
}
}
And how I'd like to use it:
var myVar = new MyAsyncBackgroundJob<string> {
ExecutePropAsync = (string s) => {
string output = null;
// this example works:
if (s == "example") output = s + s;
// this example DOESN'T works as compiler says _myVariable not found:
if (_myVariable == 1) output = s + s;
// this example DOESN'T works as compiler says MyProp not found
if (MyProp == 1) output = s + s;
return Task.FromResult(output);
}
};
// Note: in the real life ExecuteAsync(TExecuteArgs args) is called automatically by the framework
await myVar.ExecutePropAsync("example");
Firstly you are wrong. The variable
anonymousis not anonymous, it is strong typed asMyAsyncBackgroundJob<string>, but the lambda expression does indeed generate an anonymous type (more accurate: an unspeakable type).Your problem is because you try to refer to the properties of
MyAsyncBackgroundJob<string>within the scope of the lambda expression, Unlike within the scope of the class definition, there is no implicitthisobject in that scope, you must provide a reference of the object likeobj.MyProp.But when you use the object initializer like this:
var obj = new MyAsyncBackgroundJob<string>{}, actually, this variableobjwill only be assigned after the object initializer is completed, so you are not able to access it in the lambda expression. You can pre initialize it.However, no matter what,
job._myVariablewon't work, because you cannot access protected fields/properties outside the scope of the class definition.