Case Analysis of C Packing and Unpacking Operation

  • 2021-11-02 02:01:37
  • OfStack

This article illustrates the C # packing and unpacking operations. Share it for your reference, as follows:

1. Boxing in C #

Boxing in C # implicitly converts a value type to an object type using a copy of the value instead of a reference, as can be seen from the following example:


using System;
public class Test
{
  public static void Main(String[] args)
  {
    int i = 10;
    // Object of the value type i Packing 
    // 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)
    {
     Console.WriteLine(" The data has been boxed !");
    }
    // We change here i Value of 
    i = 33;
    Console.WriteLine("int i The current value is :{0}",i);
    Console.WriteLine("int i The boxed value is :{0}",obj);
  }
}

2. Unpacking in C #

Unpacking in C # is to explicitly convert an object type to a value type. Note that the type to be converted must be compatible with the value type. Examples are as follows:


int i = 10;
object obj = i;
int j = (int)obj;

What should be noted here is:

Packing and unpacking greatly affect the performance of programs, so packing and unpacking operations should be avoided in the code. You can use generics to reduce such operations.

More readers interested in C # can check the topic of this site: "C # Form Operation Skills Summary", "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Programming Thread Use Skills Summary", "C # Operating Excel Skills Summary", "XML File Operation Skills Summary in C #", "C # Data Structure and Algorithm Tutorial", "C # Array Operation Skills Summary" and "C # Object-Oriented Programming Introduction Tutorial"

I hope this article is helpful to everyone's C # programming.


Related articles: