types – Initializing PODs in C# – best practice – Education Career Blog

As far as I know*, C# defaults the plain-old-data-types (int, float, bool, etc) to sensible values. int a, float b, and bool c take on the values 0, 0.0f, and false, respectively.

Assuming this is so:

Should I explicitly give my variables values of 0, 0.0f, and false for clarity, or should I leave the values implicit, thus reducing the amount of code I write, (arguably) reducing the number of errors I can introduce into the program?

* To be honest, after 10 minutes of googling, I’m struggling to find the relevant documentation that confirms this! If anyone points it out to me I’ll amend the question!

,

C# does not assign any default value to local variables. Those defaults only apply to fields (class members).

If you don’t assign a value to your local variable before first use, you’ll get a compile time error:

static void Test() {
   int x;
   Console.WriteLine(x); // compile time error.
}

,

I would say do not initialize them (fields). It will be abundantly clear what is happening without them.

I would also say to not initialize local variables until you having a meaningful value for them, e.g. I often see code that resembles the following example:

private void SomeMethod()
{
    SomeObject myObj = null;

    if (SomeCondition)
    {
        myObj = someValue;
    }
    else if (SomeOtherCondition)
    {
        myObj = someValue;
    }
    else
    {
        myObj = someOtherValue;
    }
}

The null assignment is redundant, but I actually feel that it is damaging as if we forgot to assign to myObj in one of the code paths, e.g. if we assigned to yourObj rather my myObj in the else, then we would end up with myObj set to null which would ultimately manifest as a null reference exception at some later point during runtime. Without the inital null assignment then this would be a compile error — much easier to deal with.

,

For static/instance variables and array elements, yes it does default them appropriate. See section 5.2 of the C# 3.0 spec:


The following categories of variables are automatically initialized to their default values:

  • Static variables.
  • Instance variables of class instances.
  • Array elements.

The default value of a variable depends on the type of the variable and is determined as follows:

  • For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor (§4.1.2).
  • For a variable of a reference-type, the default value is null.

Initialization to default values is typically done by having the memory manager or garbage collector initialize memory to all-bits-zero before it is allocated for use. For this reason, it is convenient to use all-bits-zero to represent the null reference.


Local variables don’t matter as they can’t be used before being definitely assigned anyway.

As to whether you should explicitly initialize them or not, it’s mostly a matter of personal preference. I wouldn’t normally assign a value in the declaration if it’s going to be reassigned in a constructor, for example.

It’s really not a topic I can get excited about in terms of readability, to be honest.

,

Member variables are initialized to their default value (i.e. zero or null).

If you assign the default value to a member variable and do code analysis, it catches this and gives you a DoNotInitializeUnnecessarily warning.

,

Subjective Answer Below 🙂

I feel like initializing member variables to their default values should not be done. It is redundant and doesn’t add much / any value to the code.

I find that most people who do this have a strong background in C++ and consequently have it ingrained into their mind that you must initialize member variables in order to write correct code (I am guilty here). As such this practice just translated over to C# where it is not actually necessary.

But it’s not something I lose a lot of sleep over. If people default initialize their variables I may add a nitpick comment in the code review but I don’t really take a hard stance on it.

,

When the CLR initializes a primitive type it does so by zeroing out all the bits for that type. So as far as the CLR is concerned the following:

int i;
bool b;

is equivalent with this:

int i = 0;
bool b = false;

The C# compiler however reuires that you initialize a variable before you use it in an expression. I always found this a bit strange but those are the rules.

,

Having a constant exposure to many different programming languages, I will never trust a compiler/interpreter to assign default values to variables for me. Doing that myself is trivial, and ensures that a variable is not initialised:

  • with random data hanging around in memory
  • by user input fields, which is a potential security risk, especially when that data is used when interacting with a database or, worse, with the operating system

Leave a Comment