• 0

field initialization in C#


Question

What's the difference between initializing a class field at the point of declaration and initializing it in the constructor, beside syntax? Is one of these alternatives preferable?

class myClass {
	Object o;
	public myClass() {
		o = new Object();
	}
}

VS

class myClass {
	Object o = new Object();
	public myClass() {
	}
}

Thanks.

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

I think its better practice to initialise the variable in the constuctor because thats where all initialisations go in my mind, but then I'm not a pro at C# so I'm not sure if thats the standard practice, it just makes more sense to me really. Don't want to initialise half the variables outside the constructor and the rest inside.

Link to comment
Share on other sites

  • 0

The only concrete benefit is that if you have multiple constructors, you don't have to keep adding initialization to the constructors. Inline initialization is preferred in that case, but it's really a matter of taste. Initializers also execute before construction, and executed in the order declared in your class. Don't forget that initializing value types to values equal to their defaults is redundant, ergo, inefficient.

int x; // initializes to 0
int x = new int(); // also initializes to 0, but also causes an initobj IL, and a box and unbox operation.
int x = 0; // also redundant. more overhead since the system does this for you

I highly recommend getting a copy of Effective C# and More Effective C# by Bill Wagner. He goes over a lot of this kind of stuff.

HTH.

Link to comment
Share on other sites

  • 0

If you wanted to overload the constructor to have one that created an object with different arguments it would waste your declaration.

No biggy in this case, but it means that you have to consider the effects of pre-constructor code when creating the constructors.

Chris

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.