CallumVass
CallumVass

Reputation: 11448

Initialising Instance Variables

I was wondering what is the difference between the following and which way is the best way of doing it:

public class ClassA
{
    public ClassB myClass = new ClassB();

    public void MethodA()
    {
         myClass.SomeMethod();
    }
}

Or this:

public class ClassA
{
    public ClassB myClass = null;

    public ClassA()
    {
        myClass = new ClassB();
    }        

    public void MethodA()
    {
         myClass.SomeMethod();
    }
}

Edit

I removed IDisposable, bear in mind this was just an example, my point was just to see which way is better at instantiating instance variables

Upvotes: 3

Views: 79

Answers (3)

Servy
Servy

Reputation: 203821

The code in your first example will be converted into code in your second example by the compiler. When you initialize instance variables where they are defined it actually moves that initialization to the top of the constructor (or some other method just before the constructor, which is effectively the same thing).

There are some times where you can't do the first case (what you're assigning is just too complex, or relies on data that doesn't exist yet). But other than that, it's just personal preference. It's generally best to avoid mixing the two techniques in the same class though, as it's a bit harder to follow for a reader.

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

Is ClassB disposable? If so then you should be disposing of it rather than setting it to null. Does ClassA have any other resources that are disposable? If so, they should be disposed. If there is nothing to dispose of, then you need not implement IDisposable.

Just because ClassA implements disposal does not mean just anything can be disposed in that context. The thing has to implement it too. Further, if you were actually implementing IDisposable then there is a recognised pattern for doing so.

Upvotes: 1

SLaks
SLaks

Reputation: 887385

Neither.

You should not implement IDisposable unless you have actual resources to dispose.
Simply setting fields to null in Dispose() is almost always useless.

To answer the question, it doesn't matter.
You should use the shorter, simpler first version.

Upvotes: 4

Related Questions