Creating the int datatype object. [Resolved]

Posted by Allemahesh under C# on 8/19/2013 | Points: 10 | Views : 1598 | Status : [Member] [MVP] | Replies : 5
I have small doubt. Please see the below code:-
int x = new int();
x = 10;
int y = 10;
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadLine();

OutPut:
10
10

Now my question is what is main different between assign the values to int y = 10 and x = 10. Here x is you int object.
Can any tell me?




Responses

Posted by: Ssj_Kumar on: 8/19/2013 [Member] Starter | Points: 50

Up
0
Down

Resolved
"new" doesn't imply "create object on the heap" in C# - it just implies
"call the constructor". For value types, that doesn't create a new
object, it just initializes a new value.

int is a structure they never are placed on the heap

and you missed one more
int Z = default(int);
it will also react like int x=new int();

please have a look on below link where you can see the IL code of int
http://stackoverflow.com/questions/5746873/where-and-why-use-int-a-new-int

Regards,
Jayakumar Selvakani

Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 8/20/2013 [Member] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
The following link will clear your doubts...
http://bytes.com/topic/c-sharp/answers/841149-int-number-new-int

Refer joejake's last post in the link http://forums.asp.net/t/1740838.aspx/1?Difference+between+int+new+int+

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ssj_Kumar on: 8/20/2013 [Member] Starter | Points: 50

Up
0
Down

Resolved
Int is not a class it is struct so it always Value type.
please refer my post below
http://www.dotnetfunda.com/forums/thread15984-int-data-type-is-value-type-then-why-new-int.aspx

Regards,
Jayakumar Selvakani

Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Allemahesh on: 8/19/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Dear Jayakumar,
As you said that, "new" key world just implies "call the constructor". So we are calling the int class constructor. This means that int is a class and class is always reference type?
Can you clear my doubts?


Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: krrishbiju-15589 on: 8/20/2013 [Member] Starter | Points: 25

Up
0
Down
Hi ,
Please note this examples,

int x=10; Allocates an int on the stack and sets its value to 10.
int x=new int(); Allocate an int on the stack and set the value as default ie. 0.
int x; Allocates an int on stack and does not initialize it.
int x=5; Allocates an int on stack and sets it to 5;
int x=new int(5);: does not compile.



Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response