Home »
.Net »
C# Programs
Unboxing Example in C#
Learn about the unboxing and its C# implementation.
Submitted by Nidhi, on August 18, 2020 [Last updated : March 21, 2023]
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.
C# program to demonstrate the example of unboxing
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.
C# Basic Programs »