Sign in to follow this  
demongunsman

What is the difference in these 2 variables?

Recommended Posts

When declaring a variable why should I use this:

 

[source]int a = new int();[/source]

 

rather than:

 

[source]int a;[/source]

 

 

I apologize if it is syntactically incorrect, but if you get the drift of what I am trying to ask, please let me know. Is it because of the way the variable or the value in the variable is stored in the memory? Maybe it makes it more efficient?

Edited by demongunsman

Share this post


Link to post
Share on other sites

Microsoft offers a clear explanation here. The important part is under the initializing value types section. Basically, the first way doesn't initialize the variable and you must initialize variables bofore you can use them in C#. So you have to assign a value to the variable before you could use it or you'll get a compiler error.  The second way calls the default constructor for an int type which that links says is equivalent to doing this: int a = 0;

 

I doubt there's any performance difference between the two methods.

Edited by nobodynews

Share this post


Link to post
Share on other sites

You really shouldn't use the former over the latter. There's really no point, speed or otherwise. The only time you would want to invoke new for a type would be for arrays, structs, or classes. When it comes to those, invoking new is the only way you can create an instance of them.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this