Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this object initialiser pattern called?

Tags:

c#

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());
    ...
}
like image 742
Mark Cooper Avatar asked Apr 08 '16 07:04

Mark Cooper


1 Answers

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)
{
    ...
}
like image 86
Jon Skeet Avatar answered Nov 10 '22 19:11

Jon Skeet