Can't use 'this' in member initializer?

Is it legal? Does it contain a hidden error or flaw? Visual Studio does not give any errors or warnings, but ReSharper does:

/// <summary> /// immutable tuple for two /// </summary> public class Pair<TValue1, TValue2> : Singleton<TValue1> { public TValue2 Value2 { get; private set; } public Pair(TValue1 value1, TValue2 value2, Func<Pair<TValue1, TValue2>, String> toStringFunc) : this(value1, value2, () => toStringFunc(this)) { } //Red light }2> : Singleton<TValue1> 
+8
c # lambda anonymous-methods
Jan 07 '10 at
source share
3 answers

I am sure I heard that this is a compiler error fixed in the next version. I just start my 4.0 VM with a simpler test script:

 class Foo { public Foo() : this(delegate { this.Bar(); }) { } public Foo(Action foo) {} public void Bar() {} } 

works in VS2008, but in VS2010:

Error 1 The keyword 'this' is not available in the current context

+9
Jan 07 '10 at 21:05
source share

This is a bug in the C # 3 compiler, which is fixed in C # 4.

Edit:
Corner case of using lambdas expression in base constructor

+3
Jan 07 '10 at 21:05
source share

Your constructor will loop forever until the stack pops up. This is because it continues itself recursively. Try to split it:

 public Pair(TValue1 value1, TValue2 value2) : this(value1, value2, () => toStringFunc(this)) { } public Pair(TValue1 value1, TValue2 value2, Func<Pair<TValue1, TValue2>, String> toStringFunc) { /* some actual logic */ } 
0
Jan 07
source share



All Articles