×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

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 »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.