C # Value Type example of reference type differences
the value type is usually allocated on the stack, and the reference type is always allocated on the managed stack. A variable of the reference type usually contains a pointer to the instance through which the variable references the instance, the following is an example in the book. You can understand the differences between the two types..
Public partial class _ default : system. web. UI. page
{
// <Summary> class Yes reference type </Summary>
Public Class Reftype
{ Public IntVaR; }
// <Summary> struct Yes Value Type </Summary>
Public Struct Valuetype
{ Public IntVaR; }
// <Summary> testvalueref The difference between the value type and the reference type is tested. </Summary>
Private VoidTestvalueref ()
{
ReftypeReft =New Reftype();// Instance Object of reference type defined
ValuetypeValuet =New Valuetype();// Instance Object with value type defined
Reft. Var = 100;// Assignment
Valuet. Var = 100;// Assignment
Response. Write ("Reftype: Var ="+ Reft. var. tostring () +"<Br>");// Output
Response. Write ("Valuet: Var ="+ Valuet. var. tostring () +"<Br>");// Output
// <Summary> Assign a value to a new instance object </Summary>
ReftypeRefto = reft;
ValuetypeValueo = valuet;
// <Summary> Assign values to new instance objects </Summary>
Refto. Var = 10;
Valueo. Var = 1000;
// <Summary> At this time Refto. Var = 10, Hosted on the stack Var = 10, reft And Refto All point to the same address, so their values are the same , Value Type Valuet And Valueo All exist in the stack, and the values are not changed. </Summmary>
Response. Write ("Reftype: VaR Before Modification =" + Reft. var. tostring () +"<Br>");
Response. Write ("Reftype: VaR After modification =" + Refto. var. tostring () +"<Br>");
Response. Write ("Valuet: VaR Before Modification =" + Valuet. var. tostring () +"<Br>");
Response. Write ("Valuetvar After modification =" + Valueo. var. tostring () +"<Br>");
}
Protected VoidPage_load (ObjectSender,EventargsE)
{
Testvalueref ();
}
}
Result:
Reftype: Var = 100.
Valuet: Var = 100
Reftype: VaRBefore Modification= 10
Reftype: VaRAfter modification= 10
Valuet: VaRBefore Modification= 100
ValuetvarAfter modification= 1000