Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a 'var' to null

Tags:

c#

var

null

Is there any difference in runtime performance between the following variable initializations?

var    x = null as object;
var    x = (object) null;
object x = null;
like image 305
sharpener Avatar asked Mar 07 '14 08:03

sharpener


People also ask

Can you initialize a variable to null?

You should initialize your variables at the top of the class or withing a method if it is a method-local variable. You can initialize to null if you expect to have a setter method called to initialize a reference from another class.

How do you declare a variable as null?

You can make it like this. string y = null; var x = y; This will work because now x can know its type at compile time that is string in this case.

Can var be null?

var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

Can we assign null to var in C#?

In C#, you can assign the null value to any reference variable. The null value simply means that the variable does not refer to an object in memory.


2 Answers

I believe no, since there is no difference in compiled IL.

var    x = null as object;
var    x1 = (object)null;
object x2 = null;

gets compiled to

IL_0001:  ldnull      
IL_0002:  stloc.0     // x
IL_0003:  ldnull      
IL_0004:  stloc.1     // x1
IL_0005:  ldnull      
IL_0006:  stloc.2     // x2

You can see all the locals are initialized to null using ldnull opcode only, so there is no difference.

like image 183
Sriram Sakthivel Avatar answered Sep 23 '22 03:09

Sriram Sakthivel


First of all: No, I believe these three calls are essentially equivalent.

Secondly: Even if there was any difference between them, it would surely be so minuscule that it would be completely irrelevant in an application.

This is such a tiny piece of any program, that focusing on optimization here and in similar situations, will often be a waste of time, and might in some cases make your code more complicated for no good reason.

There is a longer interesting discussion about this on the programmers.stackexchange site.

like image 45
Kjartan Avatar answered Sep 23 '22 03:09

Kjartan