Why does the first constructor in ClassA cause the compiler error ‘cannot use ‘this’ in member intializer’?
… or how can i get this to work?
Thanks
public sealed class ClassA : IMethodA { private readonly IMethodA _methodA; public ClassA():this(this) {} public ClassA(IMethodA methodA) { _methodA = methodA; } public void Run(int i) { _methodA.MethodA(i); } public void MethodA(int i) { Console.WriteLine(i.ToString()); } } public interface IMethodA { void MethodA(int i); }
You can’t use the
thiskeyword when chaining constructors essentially becausethisrefers to an object that hasn’t been instantiated yet (creation of the object doesn’t begin until some (the top-level or base) constructor block has been entered). Moreover, why exactly would you want to do this? It seems rather pointless when you have access to thethiskeyword everywhere.I recommend simply using independent constructors as such:
Perhaps I misunderstand what you’re trying to do, but hopefully that will solve the issue for you.