In this article, I will discuss Object Type, Boxing, and Unboxing in C#.
Object Type, Boxing, and Unboxing
Object is the ultimate base class of all the classes in .NET Framework. Object type is the root data type that can contain a value of any data type, value type, reference type, user type or predefined. We have to typecast the value before assigning to object type.
When we change a value type variable to object type, it is said to be boxing. On the other hand, when we change an object type variable to value type, it is said to be unboxing.
For more understanding, see the example shown below.
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- class TutShare
- {
- public int value1 = 10;
- public string value2 = "qwertyuiop";
- public void Share()
- {
- Console.WriteLine("Inside Share method");
- }
- public void UnBoxingExample()
- {
-
- object o = "yeepy";
-
-
- string text = (string)o;
- }
- }
- static void Main(string[] args)
- {
- Console.WriteLine("hello Tutpoint");
-
-
- TutShare tutShare = new TutShare();
-
-
- object obje = 1000;
- Console.WriteLine(obje);
-
-
- obje = tutShare.value1;
- Console.WriteLine(obje);
- Console.WriteLine(obje.GetType());
-
-
- obje = tutShare.value2;
- Console.WriteLine(obje);
- Console.WriteLine(obje.GetType());
-
- object objTutShare = new TutShare();
-
- tutShare = (TutShare)objTutShare;
- tutShare.Share();
-
- tutShare.UnBoxingExample();
-
- Console.ReadLine();
- }
-
-
- }
-
- }
The example shown above shows how to perform Boxing and Unboxing and how the object type is used.
The output of the above program is -
- hello Tutpoint
- 1000
- 10
- System.Int32
- qwertyuiop
- System.String
- Inside Share method