Mert Özoğul
Mert Özoğul

Reputation: 320

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).

Upvotes: 0

Views: 205

Answers (2)

RadioSpace
RadioSpace

Reputation: 952

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
    }
}

Upvotes: 1

Eyal Perry
Eyal Perry

Reputation: 2285

It seems to me that the lines of code are within the class declaration. You can declare and initialize variables there, which you do in the first two lines. You can not, however, do more than that in the class scope.

The last two lines are valid only within the scope of a method.

Upvotes: 0

Related Questions