Can I somehow get a reference to the instance I am creating using object initialiser
var x = new TestClass
{
Id = 1,
SomeProperty = SomeMethod(this)
}
“this” should point to the new TestClass instance I’m creating. But it obviously refers the the instance of the class in which this code resides.
I’m not asking if this is a good way to do this.
I’m aware that I can do this like this:
var x = new TestClass {Id= x};
x.SomeProperty = SomeMethod(this);
I have a complicated scenario, in which a reference to the new instance in the object initialiser would make life easier.
Is this possible in any way?
There’s no way around it, the C# specification explicitly says that “It is not possible for an object or collection initializer to refer to the object instance being initialized.”
As for why it’s impossible, I suspect that there’s just no nice way to implement it. We want some syntactic sugar equivalent to
We just need a keyword to refer to
tempwithin the initializer, but none is easily available. We can’t usethisbecause it already means something outside the initializer. ShouldSomeProperty = this.SomeMethod(this)be equivalent totemp.SomeProperty = this.SomeMethod(temp)ortemp.SomeProperty = temp.SomeMethod(temp)? The second is consistent, but then what happens if we need the first?We could try to use
x, though we can only pick a name if the new object is immediately assigned to a variable. However, we now can’t refer to the old value ofxinside the initializer, doing the equivalent oftemp.SomeProperty = SomeMethod(x).We could reuse the
valuekeyword from property setters. This sounds good sincevaluealready stands in for the missing parameter if you consider a property getter to be syntactic sugar for aset_SomeProperty(value)method. Using it to also refer to the missing variable in the object initializer looks promising. However, we could be creating this object inside a property setter, in which casevalueis already being used, and we need to be able to dotemp.SomeProperty = SomeMethod(value).It looks like we’ll have to create a new keyword just for this purpose, maybe
newthis. However, this is a breaking change to the language because any code that has a variable callednewthisdoesn’t work any more. Microsoft generally needs a really good reason to introduce breaking changes, so it’s better to forbid access to the object being initialized.