Initializing Instance Variables

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

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

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

Or that:

public class ClassA
{
    public ClassB myClass = null;

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

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

Edit

I deleted IDisposable, keep in mind that this was just an example, my task was to see which path is better when instantiating instances

+3
source share
3 answers

None.

Cannot be used IDisposableif you do not have real resources for disposal.
Just setting fields nullin is Dispose()almost always useless.

To answer the question, it does not matter.
You should use a shorter, simpler first version.

+4
source

ClassB ? , , null. ClassA - , ? , . , IDisposable.

, ClassA , , -. . , IDisposable, .

+1

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

There are several times when you cannot make the first case (what you assign is too complicated or relies on data that does not yet exist). But other than that, it's just a personal preference. Generally, it is better to avoid mixing the two methods in the same class, although this is a bit more difficult for the reader.

+1
source

All Articles