Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use 'this' in member initializer?

Is this legal? Does it contain a hidden bug 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>
like image 734
Maslow Avatar asked Jan 07 '10 21:01

Maslow


People also ask

What is member initializer list in c++?

Member initializer list is the place where non-default initialization of these objects can be specified. For bases and non-static data members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.

How to initialize a class in constructor c++?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.

Can't be accessed in an initializer?

To Solve The instance member 'x' can't be accessed in an initializer you just have to move avg_rating initialization into a constructor. Here we can't direct assign productReviews before Class initialized the object.


2 Answers

I'm pretty sure I've heard that this is a compiler bug, fixed in the next release. I'm just firing up my 4.0 VM, with a simpler test-case:

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

works in VS2008, but in VS2010:

Error 1 Keyword 'this' is not available in the current context

like image 199
Marc Gravell Avatar answered Sep 27 '22 17:09

Marc Gravell


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

Edit:
Corner case in using lambdas expression in base constructor

like image 28
Tinister Avatar answered Sep 27 '22 19:09

Tinister