casting an object to a type

G

Guest

Can someone explain how to cast an object to a specific type during runtime?

// This line of code tells me the objects type.
System.Type type = System.Type.GetType("string of the type");

// This line of code compares the objects, but the compiler doesn't like my
casting.
return ((type)object1 <= (type)object2) ? true : false;

The compiler doesn't like my casting of (type)object1 or (type)object2.

Steve
 
J

Jon Skeet [C# MVP]

Steve Teeples said:
Can someone explain how to cast an object to a specific type during
runtime?

Casts are there for the compiler, really - they don't make sense to
perform at runtime.
// This line of code tells me the objects type.
System.Type type = System.Type.GetType("string of the type");

// This line of code compares the objects, but the compiler doesn't like my
casting.
return ((type)object1 <= (type)object2) ? true : false;

The compiler doesn't like my casting of (type)object1 or (type)object2.

No, it wouldn't. If your objects definitely implement IComparable, you
should cast both sides to that and call Compare - that should give the
same effect.
 
G

Guest

All my objects will be base numeric types (e.g., Int32, UInt64, etc.) . How
do I use IComparable? I've never used it before?
 
G

Guest

I've played with it and figured it out. Thanks Jon for your help at such a
late hour.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top