Friday, February 6, 2015

Difference Between declarations int i and int i=new int() in C#

In this post i would like to share the difference between following declarations in C#

declaration 1:
int i;
declaration 2:
int i=new int();
       In both of these declarations i is declared as a variable of type integer without any problem,
but there are some differences.

           After the declaration 1, if you would like to do any operation on i as follows or any other operation before it get initialised.
i=i*i;
you will get compiler error as follows
use of unassigned local variable'i'
you need to initialise the integer variable before doing any further operation on the variable after this declaration.

     But in declaration 2,variable i is initialised by creating an instance of class Int32[ie new int()].so it will get a default value of int(ie 0) from constructor of Class Int32.So you don't need to initialise the variable to any other unless it is necessary  before doing any operation on the variable i.
           Default value of Boolean is False and that of character is '\0'.To see default values of all data types in C# click here [from msdn].

Done ;)
»Keep Sharing and Learning«

video tutorial

5 comments: