Jump to content

  • Log In with Google      Sign In   
  • Create Account


What is the difference in these 2 variables?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 demongunsman   Members   -  Reputation: 136

Like
0Likes
Like

Posted 02 February 2013 - 09:05 PM

When declaring a variable why should I use this:

 

int a = new int();

 

rather than:

 

int a;

 

 

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, 02 February 2013 - 09:10 PM.


Sponsor:

#2 nobodynews   Crossbones+   -  Reputation: 1795

Like
3Likes
Like

Posted 02 February 2013 - 09:38 PM

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, 02 February 2013 - 09:44 PM.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!


#3 Flimflam   Members   -  Reputation: 657

Like
0Likes
Like

Posted 05 February 2013 - 09:10 PM

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.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS