Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different kinds of object initialization

Hi I was wondering if there is any difference between initializing object like this

MyClass calass = new MyClass()
{
  firstProperty = "text",
  secondProperty = "text"
}

and initializaing object like this

MyClass calass = new MyClass   // no brackets
{
  firstProperty = "text",
  secondProperty = "text"
}

I was also wondering what is the name of this kind of initialization

like image 774
Berial Avatar asked Mar 01 '11 23:03

Berial


People also ask

What is object initialization?

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.

How many types of initialization are there in Java?

Java offers two types of initializers, static and instance initializers.


2 Answers

Nope, absolutely no difference. In both cases you're using an object initializer expression. Object initializers were introduced in C# 3.

In both cases, this is exactly equivalent to:

// tmp is a hidden variable, effectively. You don't get to see it.
MyClass tmp = new MyClass(); 
tmp.firstProperty = "text";
tmp.secondProperty = "text";

// This is your "real" variable
MyClass calass = tmp;

Note how the assignment to calass only happens after the properties have been assigned - just as you'd expect from the source code. (In some cases I believe the C# compiler can effectively remove the extra variable and rearrange the assignments, but it has to observably behave like this translation. It can certainly make a difference if you're reassigning an existing variable.)

EDIT: Slight subtle point about omitting constructor arguments. If you do so, it's always equivalent to including an empty argument list - but that's not the same as being equivalent to calling the parameterless constructor. For example, there can be optional parameters, or parameter arrays:

using System;
class Test
{
    int y;

    Test(int x = 0)
    {
        Console.WriteLine(x);
    }

    static void Main()
    {
        // This is still okay, even though there's no geniune parameterless
        // constructor
        Test t = new Test
        {
            y = 10
        };
    }
}
like image 194
Jon Skeet Avatar answered Oct 13 '22 11:10

Jon Skeet


Nope. In fact, ReSharper would complain that the brackets of a parameterless constructor with initializer are redundant. You would (obviously) still need them if you were using a constructor with one or more parameters, but since this isn't the case just remove them.

like image 31
KeithS Avatar answered Oct 13 '22 12:10

KeithS