what is the objective of the boxing and unboxing methods, and what are the differences between have a value type and a reference type
i mean what can i do whit boxing, that i can't do whit out it.
thanks.
Randolf Rincon
Bucaramanga, Colombia.
Randolf, I am going to try to give you a simplified explaination rather than get into too much details.
In C# there are two kinds of Types
1) Value Types - These consist of user defined struct, enum and other premetive types like int, long, short, bool etc. Value types are types that directly hold their data. Hence when ever you make a copy of the Value Type the actual data gets copied.
Example:
int i = 10 ; int j = i ; // Copy the actual data j = 12; // Change the value of J Console.WriteLine("The value of i is {0} and the value of j is {1}",i,j); // Output //The value of i is 10 and the value of j is 12 |
Uri i = new Uri("//www.contoso.com/" href="http://www.contoso.com/">http://www.contoso.com/"); // Create a new Uri class Uri j = i ; // Copy the reference of i into j j = new Uri("http://www.mastercsharp.com"); // Change j's reference to a new Uri Console.WriteLine("The value of i is {0} and the value of j is {1}",i,j); // Output //The value of i is http://www.mastercsharp.com and the value of j is //http://www.mastercsharp.com |
int i = 10 ; object obj = i ; // Boxing i (a value type) int j = (int)obj ; // unboxing tha data from obj (a reference type) // Note the explicit cast required while unboxing Console.WriteLine("The value of i is {0} and the value of j is {1}",i,j); // Output //The value of i is 10 and the value of j is 10 |
CaptaiNdotNeT wrote:
Hello, and first of anything please forgive me if my question is very basic, i'm new to the c# programming, and to programming also, and i'm reading inside c# book, but i dont understand:
what is the objective of the boxing and unboxing methods, and what are the differences between have a value type and a reference type
i mean what can i do whit boxing, that i can't do whit out it.
thanks.
Randolf Rincon
Bucaramanga, Colombia.
Hi,
Boxing and Unboxing aren't methods you explicitly have to call, but conversion of a value-type to reference type is valled 'boxing' and from reference type to value-type is called 'unboxing'. It's done behind the scenes.
One more thing to note is that you can 'unbox' only a variable which has been boxed before e.g.
int i = 100;
object o = (object)i; // boxing
i = (int) o //unboxing
Hope that helps.