This question already has an answer here:
generally i instant initialize
an object
when adding it to a list
with this way --->
list.add(
new foo() { // <--- foo()
field1 = value1,
field2 = value2
}
);
but once i just tried --->
list.add(
new foo { // <--- foo
field1 = value1,
field2 = value2
}
);
& it worked !!!
in the 2nd way i am just creating
an object
without using ()
at tail of it.
so does anyone have any idea about the difference between these various ways to initializing an object ?
There's no difference at all. In both cases you're using an object initializer, and if you don't specify any constructor arguments, that's exactly equivalent to providing an empty list of constructor arguments. From section 7.6.10.1 of the C# spec:
Note that when you just invoke a constructor without using an object initializer (the braces) you have to specify the constructor arguments. So:
The "valid" lines are all exactly equivalent, including any use of default parameters - so
Foo
might only have a constructor like this:See section 7.6.10 of the C# 5 spec for more details.
No difference whatsoever. In an object initializer of the second form (no parentheses) the parameterless constructor is used by default, but can be specified explicitly. If you want to pass parameters to the constructor you must use the first form (with some values, obviously).
They are both object initializers. There is no difference. It's a good question though. I would think that behind the scenes the result is the same.... Compiler creates object with empty constructor and sets properties.
As Explained mostly, no difference in both. Whenever we create object always there is default constructor created without any parameter, which initialize members of object with default values(empty/NULL), means your second method will be used. But when we pass parameter at the time of object initialization the constructor must be defined for the the matching definition else it will result in syntax error. If there is no constructor defined for matching definition then there is nothing to pass as values or to initialize object members.