Jump to content
  • Advertisement
Sign in to follow this  
demongunsman

What is the difference in these 2 variables?

This topic is 2082 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!