views:

424

answers:

4

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");
+4  A: 

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";
Marc Gravell
I'm actually using Managed C++ and this doesn't compile. I think anything possible in C# should be possible in MC++ though?
Nick
Thanks. I didn't have the right syntax for returning a boxed value in managed C++.
Nick
You included C# as a tag, so I used C# syntax...
Marc Gravell
Yep, it was my fault. I have a c# GUI using a MC++ lib and I need to do the same thing in both but I couldn't get the syntax right for MC++.
Nick
+1  A: 
object varArray[3] = new object[3];
varArray[0] = 3.141593;
varArray[1] = -1005;
varArray[2] = "String";
John Saunders
+2  A: 

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]);
Reed Copsey
A: 

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);
    }
Nick