Click here to Skip to main content
15,917,481 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi expert


Is there any difference between following statement in C#?

int a;

int a=new int();


please explain.

Thanks & Regards
Divaker
Posted

The line
int a;

declares the int variable a. It must be initialized before use.

The line
int a=new int();

declares and initialize to 0 the int variable a.

See Value Types (C# Reference)[^].
 
Share this answer
 
Comments
Divaker @ Emerging Programmer 3-Jul-13 6:10am    
Hi Cpallini,

you provided a great link.
but here is an explanation

myInt = new int(); // Invoke default constructor for int type.

it may be i am behaving like a kid. yes i am a fresher.

if there is constructor, then there will be a class

and i have read class is reference type. then how int a =new int(). react as value type. means how and why the memory allocated into stack?
CPallini 3-Jul-13 8:01am    
It is not a class, it is a value type. Value types may have constructors too, see, for instance:
http://msdn.microsoft.com/en-us/library/ah19swz4.aspx
See here[^]

my guess is that new int() will generate a 0 and int a (without new) will generate some weird value like int max or int min values.

Create a console application and try to print it out.

C#
class Program {
    static void Main(string[] args) {
        int a;
        int b = new int();
        Console.WriteLine("a = " + a);
        Console.WriteLine("b = " + b);
        Console.ReadLine();
    }
}

Just tried it, doesn't even compile. a is uninitialized so you can't use it. You need to set a value before using a.
 
Share this answer
 
v2
VB
int a;: allocates an int on stack and does not initialize it.
int a=5;: allocates an int on stack and sets it to 5;
int a=new int();: allocates an int on stack and sets it to 0;
int a=new int(5);: does not compile.



OR


As you can see second one just initialize it and first one initialize and set . As for the IL code generated, they both get initialized in a single line
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900