Search code examples
c#typestype-conversionboxingunboxing

Assign Predefined Variable's Value To Object Type Variable In Boxing And UnBoxing Actions


I want to examine boxing and unboxing actions in C#. I defined variables in user defined class (it is my class). But when i want to use predefined varibles and then the strange error is occured. My code block like as below.

   public int i = 123;
   /*The following line boxes i.*/ 
   public object o = i; 
   o = 123;
   i = (int)o;  // unboxing

When i test this code to see boxing and unboxing action in C# and then the following error is occurred.

Error   3   Invalid token ')' in class, struct, or interface member declaration 
Error   4   Invalid token ';' in class, struct, or interface member declaration 
Error   1   Invalid token '=' in class, struct, or interface member declaration 
Error   2   Invalid token '=' in class, struct, or interface member declaration

I've never met such a mistake. I just want to use variables which i defined previously in user defined class (my class).


Solution

  • You need some sort of structure to your code:

    class foo
    {  
        public int I = 123; // is okay
        /*The following line boxes i.*/ 
        public object O = new object();
    
        foo()
        {
            // operations in a body
            O = 123;
            I = (int)O;  // unboxing
        }
    }