Question

In the .net CLR Object is the base for all class objects, but not basic types (e.g. int, float etc). How can I use basic types like Object? I.e. Like Boost.Variant?

E.g. like :-

object intValue( int(27) );
if (intValue is Int32)
    ...

object varArray[3];
varArray[0] = float(3.141593);
varArray[1] = int(-1005);
varArray[2] = string("String");
Was it helpful?

Solution

object, via boxing, is the effective (root) base-class of all .NET types. That should work fine - you just need to use is or GetType() to check the types...

object[] varArray = new object[3];
varArray[0] = 3.141593F;
varArray[1] = -1005;
varArray[2] = "String";

OTHER TIPS

Since you mentioned you're in C++/CLI, you should be able to do:

array<Object^>^ varArray =  gcnew array<Object^>(3);

varArray[0] = 3.141593;
varArray[1] = -1005;
varARray[2] = "String";

double val = *reinterpret_cast<double^>(varArray[0]);
object varArray[3] = new object[3];
varArray[0] = 3.141593;
varArray[1] = -1005;
varArray[2] = "String";

Thanks for the boxing answer. I need to box my return value, e.g.

    Object ^ createFromString(String ^ value)
    {
         Int32 i( Convert::ToInt32(value) );
         return static_cast< Object ^ >(i);
    }

I need to box the return value by casting to an Object pointer. Intuitive! :)

And retrieve as:

    void writeValue(Object ^ value, BinaryWriter ^ strm)
    {
        Int32 i( *dynamic_cast< Int32 ^ >(value) );
        strm->Write(i);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top