This article describes the C# packing and unboxing operations. Share it for your reference, as follows:
1. Packing in C#
Boxing in C# is to implicitly convert a value type to an object type. The conversion process uses a copy of the value instead of a reference., this can be seen from the following example:
using System; public class Test { public static void Main(String[] args) { int i = 10; //Box the value type i //It should be noted that the packing here uses a copy of the value object obj = i; //Check whether the packing is successful if(obj is int) { ("The data has been boxed!"); } //We're changing the value of i here i = 33; ("int iThe value now is:{0}",i); ("int iThe value of the box is:{0}",obj); } }
2. Unboxing in C#
Unboxing in C# is to explicitly convert an object type to a value type,Note: The type to be converted must be compatible with the value type.. As an example:
int i = 10; object obj = i; int j = (int)obj;
What you need to note here is:
Boxing and unboxing are very affecting program performance, and packing and unboxing operations should be avoided in the code. Generics can be used to reduce such operations.
For more information about C# related content, please check out the topic of this site:Summary of C# form operation skills》、《Tutorial on the usage of common C# controls》、《Summary of WinForm control usage》、《Summary of thread usage techniques for C# programming》、《Summary of C# operation skills》、《Summary of XML file operation skills in C#》、《C# data structure and algorithm tutorial》、《Summary of C# array operation skills"and"Introduction to C# object-oriented programming tutorial》
I hope this article will be helpful to everyone's C# programming.