I'm reviewing some code with an object initialisation pattern that I don't recognise - can anyone tell me what this pattern is called (and where to find documentation on usage)?
obj.myType = (myVar = new MyType());
In case it matters, the specific use-case is as follows;
protected MyType myVar;
protected readonly MyComplexType myComplexType;
protected void Page_Init(object sender, EventArgs e)) {
...
myComplexType.myType = (myVar = new MyType());
...
}
It's just assigning the same value twice - once to myVar
and once to myComplexType.myType
.
It's equivalent to
var tmp = new MyType();
myVar = tmp;
myComplexType.myType = tmp;
(In some complex cases there can be type conversions going on there, but I don't expect there to be any in this particular case.)
You don't need to use the extra local variable, of course. This code is "somewhat equivalent" but involves reading from myVar
so isn't exactly equivalent, but more likely to be what you'd use:
myVar = new MyType();
myComplexType.myType = myVar;
There's no specific name for this, and it's relatively rare to use the result of an assignment elsewhere in an expression, with the most common example being:
string line;
while ((line = reader.ReadLine()) != null)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With