C# Member Variable Initialization; Best Practice

C# member variable initialization; best practice?

In terms of performance, there is no real difference; field initializers are implemented as constructor logic. The only difference is that field initializers happen before any "base"/"this" constructor.

The constructor approach can be used with auto-implemented properties (field initializers cannot) - i.e.

[DefaultValue("")]
public string Foo {get;set;}
public Bar() { // ctor
Foo = "";
}

Other than that, I tend to prefer the field initializer syntax; I find it keeps things localized - i.e.

private readonly List<SomeClass> items = new List<SomeClass>();
public List<SomeClass> Items {get {return items;}}

I don't have to go hunting up and down to find where it is assigned...

The obvious exception is where you need to perform complex logic or deal with constructor parameters - in which case constructor-based initialization is the way to go. Likewise, if you have multiple constructors, it would be preferable for the fields to always get set the same way - so you might have ctors like:

public Bar() : this("") {}
public Bar(string foo) {Foo = foo;}

edit: as a side comment, note that in the above, if there are other fields (not shown) with field initializers, then they are only directly initialized in the constructors that call base(...) - i.e. the public Bar(string foo) ctor. The other constructor does not run field initializers, since it knows they are done by the this(...) ctor.

Best practice for initializing member variables?

You do not have to initialise member variables, but it does not hurt if you do. Member variables acquire their default values automatically, usually a null for objects and the default value for primitive types (such as 0 for an int).

As for having different constructors, you do not have to repeat the member initialisation in each version since you can call an overloaded constructor from any other just as you would with an overloaded method.

Regarding best practice, personally I initialise member variables in the constructor as this is where I want to "construct" my object into a stable state. In other words, even if I would have initialised member variables where I declare them, when the constructor is called, it would be as if I was wiping the slate clean.

Initialization of variables: Directly or in the constructor?

There's one potentially significant difference in some cases.

Instance initializers are executed before the base class constructor is executed. So if the base class constructor invokes any virtual methods which are overridden in the derived class, that method will see the difference. Usually this shouldn't be a noticeable difference, however - as invoking virtual methods in a constructor is almost always a bad idea.

In terms of clarity, if you initialize the variable at the point of declaration, it makes it very clear that the value doesn't depend on any constructor parameters. On the other hand, keeping all the initialization together helps readability too, IMO. I would try to make sure that wherever possible, if you have multiple constructors they all delegate to one "master" constructor which does all the "real" initialization - which means you'll only put those assignments in one place either way.

Sample code to demonstrate the difference:

using System;

class Base
{
public Base()
{
Console.WriteLine(ToString());
}
}

class Derived : Base
{
private int x = 5;
private int y;

public Derived()
{
y = 5;
}

public override string ToString()
{
return string.Format("x={0}, y={1}", x, y);
}
}

class Test
{
static void Main()
{
// Prints x=5, y=0
new Derived();
}
}

What are the best practices for Private Member Instantiation/Initialization?

It can make a difference in an inheritance situation. See this link on the object initialization order:

http://www.csharp411.com/c-object-initialization/

  1. Derived static fields
  2. Derived static constructor
  3. Derived instance fields
  4. Base static fields
  5. Base static constructor
  6. Base instance fields
  7. Base instance constructor
  8. Derived instance constructor

So if this is a derived class, the entire base object is initialized between when your derived field is initialized and when your constructor runs.

Declaring variables - best practices

If you set your variable outside of the constructor then there is no error handling (handeling) available. While in your example it makes no difference, but there are many cases that you may want to have some sort of error handling. In that case using your first option would be correct.

Nescio talked about what implication this would have on your applicaiton if there were some constructor failures.

For that reason, I always use Option #1.

C#: Initializing class variables

Instance variables that are assigned a default value as part of their declaration will get this value assigned right before the constructor is run, from the outside there is no perceptible difference in behavior between 1) and 2), it's mostly a matter of style.

You also introduce an additional InitializePerson() method in your approach 2) - this can be beneficial if you have multiple constructors that then all can use the same common initialization method (which keeps the code DRY).

Edit in response to comment, see MSDN:

Fields are initialized immediately
before the constructor for the object
instance is called. If the constructor
assigns the value of a field, it will
overwrite any value given during field
declaration.

Best Way to Initialize Class Variables in Unity

I don't thing there is a straight answer to your question, rather good practices.

First thing first, C# automatically give a default value to common types (int > 0, char > 0 ('\0'), float 0.0f, null for a reference type, ...) so you do not need to initialise those unless you've a specific behaviour which involves a specific initial value (like, giving maximum value to an int intended for a function returning a min value).
This property extends to structures (a struct containing an int and a string will automatically be initialized to 0 and null for those fields).

For reference types, and on a general manner, anything which requires custom allocation/initialisation, I usually do all of that, if possible, in constructor because, eh, that's what they are made for, making your object ready to use for extern users.

In case of Unity, initializing should also be good in Start().

Your professor way is of course acceptable. Some more piece of information :
Initialization - Stack Overflow

C# Vars init, performance and good practice


I want to know, if, in C#, ALL variables are automatically
initialized, or if there are some cases where there are not

When you declare a reference type variable like instance of SomeClass, it's default value will be null. Your variable will get initialized once you allocate some memory for it using new

SomeClass someClass; //not initialized, it's value is null

someClass = new SomeClass(); //initialized

On the other hand value types are initialized when you declare them. For example

int bar; //initialized with value 0

Is it a good practice to initialize every vars all the time or not ?

Well, it depends on scenario. For example when you declare a bool it's default value is false. But for reader's understanding it's better to explicitly do bool myBool = false. On the other hand if you have to pass a variable as out to some method, initializing a variable is of no use because it is responsibility of method. It really depends on your scenario and practises you like to follow.

Will I get troubles by not initializing those ?

If you are fine with default value(uninitialized value) then you won't get in to trouble. But if your code expects some initialized value and your variable is not initialized then you might get into trouble.

If I do initialize them, will I get performance slowdown?

Nope. If your app's performance is really slow you should use some profiler to find out what is causing slow performance. Initializing variable is very unlikely to cause performance issue



Related Topics



Leave a reply



Submit