Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
OOPS in C#
C# Data Types
Boxing and Unboxing in C#
Garbage Collection in C#
C# - Conditional Statements
C# - Loops
Interfaces in C#
Generics in C#
Collections in C#
C# 8.0 new features
C# Singleton Design Pattern
C# Factory Design Pattern
LINQ in C#
C# - Program to Find Prime Numbers
C# - Fibonacci Sequence
C# - Factorial of a number
C# - Recursive methods
C# - Anonymous Methods
C# - String Methods
C# TDD - XUnit
C# TDD - NUnit
C# Multiton Design Pattern
C# Facade Design Pattern
C# Abstract Factory Design Pattern
C# Decorator Design Pattern
C# Composite Design Pattern

Boxing and Unboxing in C#



In C#, boxing and unboxing are concepts used to convert value types to reference types and vice versa.

Boxing:

Boxing is the process of converting a value type (such as an int or double) into a reference type (object or any interface type implemented by this value type). When a value type is boxed, it is wrapped inside an object and stored on the heap instead of the stack.

Example of Boxing:

csharp
int num = 123;        // Value type
object obj = num;     // Boxed into an object

In this example, num is a value type, but when it is assigned to obj, it is boxed. The num value is stored inside the obj variable on the heap.

Unboxing:

Unboxing is the process of converting a reference type back into a value type. It explicitly extracts the value type from the object.

Example of Unboxing:

csharp
int num = 123;        // Value type
object obj = num;     // Boxed into an object
int unboxedNum = (int)obj;  // Unboxed back to a value type

In this example, obj is unboxed back into an integer type by explicitly casting it back to int.

Important Points:

  • Boxing and Unboxing Operations are Costly: These operations involve memory allocation and can degrade performance if done excessively in performance-critical code.

  • Type Safety: Unboxing requires an explicit cast, which can throw an InvalidCastException if the object being unboxed is not of the appropriate type.

Full Example:

csharp
using System;

public class Program
{
    public static void Main()
    {
        int number = 10;  // Value type
        object boxedNumber = number;  // Boxing

        try
        {
            int unboxedNumber = (int)boxedNumber;  // Unboxing
            Console.WriteLine("Unboxed Number: " + unboxedNumber);
        }
        catch (InvalidCastException e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
}

In this program, we box the integer number into boxedNumber and then unbox it back to unboxedNumber.

Boxing and unboxing provide a way to treat value types as objects when needed, but careful thought should be given to their use due to potential performance impacts. If you have any more questions or need further clarification, feel free to ask!




All rights reserved | Privacy Policy | Sitemap