casting an object to a type

  • Thread starter Thread starter Guest
  • Start date Start date
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
 
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.
 
All my objects will be base numeric types (e.g., Int32, UInt64, etc.) . How
do I use IComparable? I've never used it before?
 
Back
Top