MyObject ob = new Object(1,2);
This is building an object and doing something with values ββin the constructor. Perhaps it can set values, maybe it is not. It depends on the logic in the constructor.
MyObject ob = new Object(){ val1 = 1, val2 = 2 };
This is building the object using the default constructor and setting the initial values ββof the properties after the object was created. In this case, setting values ββhas nothing to do with the constructor, except that it is in the same expression. This is the same as:
MyObject ob = new Object(); ob.val1 = 1; ...
What is neat in this syntax is what you can do:
Object ob = new Object(){ val1 = 1, val2 = 2 };
instead of doing:
Object ob = new Object(1,2); ((MyObject)ob).val1 = 1;
because the initialization of variables occurs without touching the destination of the variable.
kemiller2002
source share