2

What is the difference between instantiating a new instance of an object like this:

public class MyClass
{
    private Order order = new Order();

    public void MethodOne()
    {
        order.CreateOrder();
    }

    public void MethodTwo()
    {
        order.RemoveOrder();
    }

    public void Dispose();
    {
        order.Dispose();
    }
}

And this:

public class MyClass
{
    private Order order;

    public MyClass()
    {
        order = new Order();
    }

    public void MethodOne()
    {
        order.CreateOrder();
    }

    public void MethodTwo()
    {
        order.RemoveOrder();
    }

    public void Dispose();
    {
        order.Dispose();
    }
}

MethodOne and MethodTwo are still using the same object right? No matter which way I use?

CallumVass
  • 11,288
  • 26
  • 84
  • 154

3 Answers3

2

This provide a default value for the object order.

private Order order = new Order();

Imagine you class have several constructors, instantiating using any of them will still make your order object initialized.


If you initialize the object in the constructor, the object order is a null reference until you initialize it yourself (like you do in the constructor).

Now keep in mind that if you add another constructor, you will have to init the object order as well in it, either by calling the default constructor, or by initializing like you are doing:

public class MyClass
{
    private Order order;

    public MyClass()
    {
        order = new Order();
    }

    public MyClass(string name)
        : this()  // either call the default constructor
    {
        // or initialize explicitely
        order = new Order();
    }

}
Didier Ghys
  • 30,396
  • 9
  • 75
  • 81
1

In practice the above would be the same. The main time it will differe is if MyClass had multiple constructors. Then you would need to make sure you add the code to each one (or call the simple constructor) whereas if its set at the delcaration then it will be initialisised no matter which constructor you use.

Chris
  • 27,210
  • 6
  • 71
  • 92
0

Imho, there is no real difference in the mentioned constructs.