Why does the compiler give an error about this being unavailable that when initializing an instance variable when defining it?
Keyword 'this' is not available in the current context
The constructor initialization is fine. I understand the scenario here - I just wanted to find the reason (via MSDN or otherwise) why "this" is available to a constructor but not directly if initializing the member variable.
Here is a simple abstraction of the error I'm seeing.
public class ClassA
{
// Gets compiler error that "this" unavailable
protected ClassB _a1 = new ClassB(this);
// Works fine
protected ClassB _a2;
public ClassA() { _a2 = new ClassB(this); }
}
public class ClassB
{
public ClassA A { get; private set; }
public ClassB(ClassA a) { this.A = a; }
}
I was hoping to keep my initialization next to the assignment since the above example is an abstraction of my code where I am defining Lazy valueFactory delegates for 10-15 member variables in which the delegates need the data context passed as a parameter to the constructor. With 15 member variables, I'd prefer to keep the assignment next to the definition on a single line instead of having 15 lines of definitions and then another 15 lines in the constructor initializing each one.
This is basically what I had to do in my actual code:
public class MyContext
{
public ProgramService Programs { get { return _programs.Value; } }
protected Lazy<ProgramService> _programs;
public MyContext()
{
_programs = new Lazy<ProgramService>(() => new ProgramService(this));
}
}