Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising Instance Variables

Tags:

c#

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

like image 203
CallumVass Avatar asked Mar 08 '26 19:03

CallumVass


2 Answers

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.

like image 174
SLaks Avatar answered Mar 11 '26 08:03

SLaks


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.

like image 27
Grant Thomas Avatar answered Mar 11 '26 08:03

Grant Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!