Skip to main content
GameDev.net gamedev.net
🔒 Locked

Initializing class variables - where/when? - C Sharp

Started by shawnre Jan 2, 2009 at 10:24 AM 4 replies 600+ views
Original Post
shawnre
shawnre
Hello all, Little code sample:


Example 1:

class Fu
{
  int bar = 0;
}

Example 2:

class Fu
{
  int bar;

  public Fu()
  {
    bar = 0;
  }
}

Which is better if either? Certain benefits to either approach? Is this just a standard that will vary from say employer to employer? Thanks for any insight!
Promethium
Promethium
I believe example 1 could be slightly better, performance wise.

In example 2, when the class is instantiated all member variables are assigned their default value. Then, in the constructor you assign the variable a new value. So in effect the variable is initialized twice. In you example 1 the variable is only assigned once.

However, the speed difference will be so small I wouldn't worry about it if I was you. Also, the compiler might recognize that the first, default assignment is never used and just optimize it away.

Trillian
Trillian
Initializing to zero, which is the default value of the System.Int32 structure (int), is plain useless and will give you a warning if you're validating your coding style with FxCop.

If you're initializing to a non-default value, then it depends. If all of your constructors would use the same constant value for initialization, you'd better assign the value as you declare the field. If different constructors use different values, or non-constant values, then assign it in the constructors. Don't forget that constructors can call eachother too, that can help avoid code duplication.

Same people don't like using assignment at declaration (a subset of them don't do this simply because they come from a language that does not support it), but I think it can make the code clearer. In the end, it's up to you.
Zahlman
Zahlman
Doesn't C# use C++-style initialization lists as well, or am I imagining things?
Telastyn
Telastyn
Quote:
Original post by Zahlman
Doesn't C# use C++-style initialization lists as well, or am I imagining things?


C# initialization lists are limited to base constructors or redirection to other class constructors.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.