3

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

0

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So both examples, ClassB will be disposed by the garbage collector?
No; the garbage collector doesn't dispose anything. They will be collected by the GC.
@BiffBaffBoff: They actually compile to identical IL.
1

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.