Possible Duplicate:
Cannot use ‘this’ in member initializer?
Any ideas why I get an error if I try to do something like this:
public class Bar
{
public Bar(Foo foo)
{
}
}
public class Foo
{
private Bar _bar = new Bar(this);
}
I get an error saying:
“Cannot use ‘this’ in member initializer”
but the following works:
public class Foo
{
private Bar _bar;
public Foo()
{
_bar = new Bar(this);
}
}
Anyone know the reason behind this? My understanding was that these would compile to the same IL, so am curious as to why one is allowed and the other isn’t.
Thanks,
Alex
I suspect it’s to prevent you from using the object before at least the base class constructor has run, ensuring that all the base class members are appropriately initialized. (Variable initializers are executed before the base class constructor, whereas the constructor body is executed after that.)
Will check whether the annotated spec has anything to say about this when I’m next near it…
EDIT: The C# 4 annotated spec doesn’t have any explanation. Just (in 10.5.5.2):