C# Program to Demonstrate Boxing Operations
Posted by Superadmin on August 11 2022 07:24:14

C# Program to Demonstrate Boxing Operations

 

 

This is a C# Program to demonstrate boxing operations.

Problem Description

This C# Program Demonstrates Boxing Operations.

Problem Solution

Here Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.

Program/Source Code

Here is source code of the C# Program to Demonstrate Boxing Operations. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Demonstrate Boxing Operations
 */
using System;
class sample
{
    int x = 10;
    object obj;
    void boxmethod()
    {
        sample s= new sample();
        bool b;
        object ob="CSHARP";
        b=s.obj is int;
        Console.WriteLine(b);
        s.obj = x;
        b = s.obj is int;
        Console.WriteLine("{0},{1},{2}",s.obj,s.x,b);
        s.x = (int)s.obj;
        s.x = 20;
        b = s.obj is int;
        Console.WriteLine("{0},{1},{2}", s.obj, s.x, b);
        s.obj="CSHARP";
        b=s.obj is int;
        Console.WriteLine("{0},{1},{2}",s.obj,s.x,b);
        Console.ReadLine();
    }
    public static void Main()
    {
        sample s=new sample();
        s.boxmethod();
    }
}
Program Explanation

This C# program is used to demonstrate boxing operations. Here boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. Boxing is used to store value types in the garbage-collected heap.

 

It is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Then boxing is a value type allocates an object instance on the heap and copies the value into the new object.

Runtime Test Cases
 
False
10,10,True
10,20,True
CSHARP,20,False