C# program to demonstrate the example of unboxing

Unboxing in C#: Here, we are going to learn about the unboxing and its C# implementation.
Submitted by Nidhi, on August 18, 2020

Here we will understand the concept of un-boxing. We will unbox the value of the object type and assign it to the variable of the basic data type.

Program:

The source code to demonstrate the unboxing in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to demonstrate the unboxing in C#

using System;

class UnBoxDemo
{
    int intVar;
    void Unbox(object Ob)
    {
        intVar= (int)Ob;
    }
    object Box(int val)
    {
        intVar = 0;
        return (object)val;
    }
    public static void Main()
    {
        UnBoxDemo D = new UnBoxDemo();
        object ObVal=10;

        D.Unbox(ObVal);
        Console.WriteLine("intVar : "+D.intVar);

        ObVal = D.Box(20);

        Console.WriteLine("ObVal : "+ObVal);
    }
}

Output:

intVar : 10
ObVal : 20
Press any key to continue . . .

Explanation:

In the above program, we created a class UnBoxDemo that contains a data member intVar of integer type, and we also created two methods Box() and UnBox() that performs boxing and un-boxing respectively. 

In the Main() method, we created the object D of UnBoxDemo class and then perform Unboxing and Boxing and print the values on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.