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.

advertisement
advertisement

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

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.