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 ?
Initialization: Assigning a value to a variable is called initialization. For example, cost = 100. It sets the initial value of the variable cost to 100. Instantiation: Creating an object by using the new keyword is called instantiation.
An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.
Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
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:
An object creation expression can omit the constructor argument list and enclosing parentheses provided it includes an object initializer or collection initializer. Omitting the constructor argument list and enclosing parentheses is equivalent to specifying an empty argument list.
Note that when you just invoke a constructor without using an object initializer (the braces) you have to specify the constructor arguments. So:
Foo foo = new Foo(); // Valid Foo foo = new Foo; // Invalid Foo foo = new Foo() {}; // Valid Foo foo = new Foo {}; // Valid
The "valid" lines are all exactly equivalent, including any use of default parameters - so Foo
might only have a constructor like this:
// You can invoke this without specifying arguments public Foo(int x = 0) { }
See section 7.6.10 of the C# 5 spec for more details.
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.
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