Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am not getting the concept of boxing and unboxing.Why I need To do this and where.
It is said boxing means conversion of value to object type
C#
int i = 3;
            object o = i;
          Console.WriteLine(o);
            Console.ReadLine();

Result is :3
Unboxing means conversion of object to value type
C#
int i = 3;
           object o = i;
           int m = (int)o;
           Console.WriteLine(m);
           Console.ReadLine();

Result is :3
I can directly also do
C#
int i = 3;
          
          
           Console.WriteLine(i);
           Console.ReadLine();

Result is :3

Why i need to have this concept..Please tell me I am not able to get what this concept actually means
Thanks in advance
Posted

First, simply read about boxing and unboxing more thoroughly and think about it.
This should be clear enough: http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx[^].

To add to it, I can only respond to your immediate concerns.

First, in all your code samples, conversion to object is completely pointless, only the last sample is reasonable. What can I add to your understanding. Even though boxing and unboxing is very important in .NET, immediate using boxing is pretty rare, and using unboxing is even more rare.

Let me explain just Write, or, very close in usage string.Format(string format, params object[] values). Look at the last method signature. This is the most universal way to provide passing parameters for formatting of the value of absolutely any type. Let's see how it works. If format string contains only placeholders in "free format" like {0}, {1}, etc., and as each parameter is boxed to System.Object, each of the placeholders is substituted with what is returned by System.Object.ToString. In other words, the mechanism uses the fact that all objects of all type have ToString method. Unboxing is already done in passing of the parameters (due to assignment compatibility to System.Object), and no unboxing is needed. If specific format specifier is used for some of the placeholders (this is called composite formatting), unboxing is needed for getting type-specific information. For example, if number of significant digits is specified, properties of floating-point arithimetic are used.

—SA
 
Share this answer
 
Comments
Firo Atrum Ventus 18-Oct-11 2:08am    
+5For the explanation and example.
Sergey Alexandrovich Kryukov 18-Oct-11 2:28am    
Thank you, Firo.
--SA
Boxing

CSS
All C# types, including the value types, are derived from object. Thus, a reference of type object can be used to refer to any other type, including value types.
When an object reference refers to a value type, a process known as boxing occurs.
Boxing causes the value of a value type to be stored in an object instance. Thus, a value type is "boxed" inside an object.
Boxing occurs automatically.
    For Ex.

C#
object obj;
            int a=10;
            obj=a;  // Boxing implicitly performs


Unboxing

Unboxing is the process of retrieving a value from a boxed object.
This action is performed using an explicit cast from the object reference to its corresponding value type.
Attempting to unbox an object into a different type will result in a runtime error

C#
int x;
object obj;
x = 10;
obj = x; // box x into an object
int y = (int)obj; // unbox obj into an int
Console.WriteLine(y);
 
Share this answer
 
Comments
shivani 2013 18-Oct-11 0:43am    
Why i need object obj;
int a=10;
obj=a;
I can simply write
int a=10;
console.writeLine(a);
i am getting same answer a=10;
then why to do this through object
Sergey Alexandrovich Kryukov 18-Oct-11 0:57am    
Of course you are right! Boxing without purpose if very bad, you should use it in very rare cases only.
--SA
Sergey Alexandrovich Kryukov 18-Oct-11 1:12am    
Anyway, I added my solution, please see.
--SA
Sergey Alexandrovich Kryukov 18-Oct-11 1:19am    
You see, this is all correct, but it does not seem to help OP, who probably knows that (but don't feel it well) and still have trouble understanding the purpose. However, it's hard to understand what could help. So, I voted 4. I tried to add my explanation in my solution, please see.
--SA
You could try and read a book on .Net development - that should give you some idea on what this is.
 
Share this answer
 
Here's a wiki page about boxing/unboxing : http://en.wikipedia.org/wiki/Object_type_(object-oriented_programming)#Boxing[^] (ps. don't look at the code)

[Edit2]Thanks to SA for the heads up, I now understand that my answer bellow are not an example of boxing. But it should give you general idea. I want to give a correct example but SA already write one so please refer to SA's solution.[/Edit2]

Don't worry, You'll get better understanding about boxing/unboxing and its uses after learning about polymorpishm.

[Edit]
Now that you've understood about polymorphism, we can make this easy.

Imagine that I have an animal class:
C#
class Animal {
    public string talk(){
        return "";
    }
}


And I have two child of animal class:
C#
class Cat:Animal {
    public string talk(){
        return "meow";
    }
}

C#
class Dog:Animal {
    public string talk(){
        return "roof";
    }
}


Now if I want to use method talk in a method in another class, I can just set the parameter to use Animal class:
C#
class MainProgram{
    static void Main(string[] args)
    {
        Cat c = new Cat();
        Dog d = new Dog();
        Animal a = c;
        write(a);
        a = d;
        write(a);
    }
    
    void write(Animal a)//we can just write it like this instead writing two method with different parameter.
    {
        Console.WriteLine(a.talk());
    }
}

[/Edit]
 
Share this answer
 
v5
Comments
shivani 2013 18-Oct-11 0:32am    
Sir, I know the concept ogf polymorphism..how this is related ?
Sergey Alexandrovich Kryukov 18-Oct-11 1:14am    
What does "don't look at the code" means? Are you serious?
--SA
Firo Atrum Ventus 18-Oct-11 1:22am    
@SA:
Yes, I'm serious. Most people that asked me this question have a better understanding of boxing/unboxing if they don't see the code (most, not all).
And he's asking about the use of boxing/unboxing, therefore the code in that page is completely useless
Sergey Alexandrovich Kryukov 18-Oct-11 1:39am    
Interesting idea, anyway. Maybe, it needs just different article, with more useful code?
--SA
Sergey Alexandrovich Kryukov 18-Oct-11 1:42am    
Sorry, wrong explanation of boxing. Write(c) is not boxing just because c is already of the class type. Probably you really mix late binding with boxing or something.

Also, it's not nice to post code which won't even compile.
Sorry, I just have to vote 1.

Please, try to understand me. Most important principle here is "don't do evil". Wrong advice is really worse than nothing. I somebody shows my mistake, I'm trying to fix it and improve myself.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900