Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbox specific struct members

Tags:

c#

Is it possible in the following example where i am boxing a struct named fraction, to then unbox a specific member of the struct for example the numerator?

using system;

struct fraction
    {
       public int numerator;
       public int denominator;
    }   

class Program
    {
        static void Main()
        {
            fraction f1;
            f1.denominator = 100;
            f1.numerator = 10;
            object obj = f1;

            // initializing f2.
            fraction f2 = new fraction();
            // Or can unbox the obj to the f2 like this.
            f2 = (fraction)obj;
            // But if i want to only unbox the numerator member of the struct fraction boxed inside the obj Something like this will not work
            f2.numerator = (fraction)obj.numerator;
        }
    }
like image 474
Johnson Avatar asked Jul 24 '26 19:07

Johnson


2 Answers

It's not possible to unbox a member or property of a boxed object without unboxing the entire object.

The object is only accessible as a System.Object while in boxed state. Any operation on the original type requires unboxing.

like image 162
CoolBots Avatar answered Jul 26 '26 10:07

CoolBots


You can't unbox an individual field without unboxing the entire object.

But maybe you just wanted to access the field, and are unsure of the correct syntax. After you unbox the original object, you can access the field by referencing the unboxed value:

fraction f2 = new fraction();
fraction originalFraction = (fraction)obj;   // unbox the object
int numerator = originalFraction.numerator;  // access the field on the unboxed fraction
f2.numerator = numerator;

You can shorten that to a single line, using object initialization, although ultimately it's doing the same thing as the above code:

fraction f2 = new fraction { numerator = ((fraction)obj).numerator };
like image 27
Grant Winney Avatar answered Jul 26 '26 10:07

Grant Winney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!