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
Neither.
You should not implement
IDisposableunless you have actual resources to dispose.Simply setting fields to
nullinDispose()is almost always useless.To answer the question, it doesn’t matter.
You should use the shorter, simpler first version.