Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating objects in the constructor

Tags:

c#

oop

Is there any benefit to doing the following:

public class Foo
{
    private Bar bar;

    public Foo()
    {
        bar = new Bar();
    }
}

Instead of doing it like so:

public class Foo
{
    private Bar bar = new Bar();

    public Foo()
    {
    }
}

Given that at instantiation, the private member variable in either example will be instantiated, I don't believe there is a difference, but I've seen it enough times to where I'm curious.

like image 253
dreadwail Avatar asked Jan 23 '11 07:01

dreadwail


People also ask

Can we create an object inside a constructor?

The answer is no. So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

What is instantiating an object?

An instance of an object can be declared by giving it a unique name that can be used in a program. This process is known as instantiation. A class can also be instantiated to create an object, a concrete instance of the class. The object is an executable file that can run on a computer.

Do constructors instantiate?

A Java class constructor initializes instances (objects) of that class. Typically, the constructor initializes the fields of the object that need initialization. Java constructors can also take parameters, so fields can be initialized in the object at creation time.


1 Answers

In the exact case you've given, there isn't a difference - but in general there is.

Variable initializers are executed before the base class constructor is called. If that base constructor calls a virtual method which uses some of the instance variables, you can see that difference.

For spec fans, it's in section 10.11.2 of the C# 4 spec:

When an instance constructor has no constructor initializer, or it has a constructor initializer of the form base(...), that constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor.

Here's an example demonstrating this:

using System;

public class Base
{
    public Base()
    {
        Dump();
    }

    public virtual void Dump() {}    
}

class Child : Base
{
    private string x = "initialized in declaration";
    private string y;

    public Child()
    {
        y = "initialized in constructor";
    }

    public override void Dump()
    {
        Console.WriteLine("x={0}; y={1}", x, y);
    }
}

class Test
{
    static void Main(string[] args)
    {
        new Child();
    }
}

Result:

x=initialized in declaration; y=

Now having said the above, I would try hard to avoid calling virtual methods from a constructor. You're basically asking the derived class to work in a partially-initialized fashion. However, it's a difference you should be aware of.

As for where to initialize variables... I have to admit I'm not particularly consistent, and I don't find that's actually a problem. If I have any specific bias, it's probably to initialize anything which won't depend on any parameters at the point of declaration, leaving the variables which I can't initialize without extra information to the constructor.

like image 131
Jon Skeet Avatar answered Oct 18 '22 01:10

Jon Skeet