Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing null variables in .NET

What is the proper way to initialize a null variable in .NET? I've been told by one of my colleagues that hard defining of a variable to null is a slowdown.

int var1;          // good practice
string s1;         // good practice

int var2 = 0;      // bad practice
string s2 = null;  // bad practice

Is that correct?

like image 890
kofucii Avatar asked Aug 28 '10 20:08

kofucii


2 Answers

Assuming you actually mean the default value instead of a null value, it could slow things down very, very slightly if you actually assign the value in the constructor instead of in the variable declaration. If it's part of the variable declaration I would probably expect the JIT compiler to remove the unnecessary assignment, as the object's memory is wiped on first initialization.

However, the chances of this being significant are absolutely tiny in either case.

Which do you find the more readable form? That's much more important in the vast majority of cases.

EDIT: Note that for static fields at least, there are subtle cases where the two don't behave the same way. Here's an example - the Test1 and Test2 classes differ only in terms of whether the y declaration has an assignment:

using System;

class Test1
{
    static int x = GetX();
    static int y = 0;

    public static void Hello()
    {
        Console.WriteLine("{0} {1}", x, y);
    }

    static int GetX()
    {
        y = 2;
        return 5;
    }
}

class Test2
{
    static int x = GetX();
    static int y;

    public static void Hello()
    {
        Console.WriteLine("{0} {1}", x, y);
    }

    static int GetX()
    {
        y = 2;
        return 5;
    }
}

class Test
{
    static void Main()
    {
        Test1.Hello();
        Test2.Hello(); 
    }
}
like image 191
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet


For an int in .net, it's actually not possible to assign null to it as it's a value type, rather than a reference type, unless you create it as an int? (Nullable<int>), which whilst it is a value type, has special semantics and can thus have null assigned to it.

In your example, there's no point assigning 0 to var2 as the default value for an int is zero. That said, I'd be quite surprised if the c# compiler (although it may be the case tha tthe compiler produces different MSIL for the two) / CLR interpreter treats both as being exactly the same.

private void MyFunction()
{
    int i;
    string s;

    if (s == "3")
    {
        if (i == 1)
        {
        }
    }
}

Bear in mind that in this, ultimately pointless, function, you'd get a compilation error for both the attempt to compare s and i as both are "unassigned locals". This is different from member variables of a class, like:

public class MyClass
{
    int i;

    public void MyFunction()
    {
        if (i == 1)
        {
        }
    }
}
like image 30
Rob Avatar answered Sep 28 '22 08:09

Rob