I think you are asking 2 different questions:
1) How do I convert an object to a type that is returned at runtime
2) How do I compare 2 objects when I do not know their type at compile time?
I separate them, because I can answer each one, but not necessarily your
original question.
To convert an object to a type that is determined at runtime, you
Covert.ChangeType(). Example:
public Type RuntimeMethodReturnsSomeType(){
return typeof(CSomeObject);
}
object object1 = Convert.ChangeType( object2,
RuntimeMethodReturnsSomeType() );
Now object2 has been converted to a CSomeObject. However, it is still
stored in an 'object' variable, so you can still only perform actions
that can be performed on an object (which does not include comparisons
using >).
If you want to compare 2 objects without knowing their type, you can
cast them to IComparable.
object a = 3;
object b = 4;
if ( ((IComparable)a).CompareTo( b ) > 0 )
{
Console.WriteLine("a is greater");
}
else
{
Console.WriteLine("b is greater");
}
If you can't guarantee that the underlying type implements IComparable,
or are the same type, you may want to do some additional checking...
object a = 3;
object b = 4;
IComparable aComparable = a as IComparable;
if ( a != null && a.GetType() == b.GetType() ) {
if (a.CompareTo(b) > 0) {
// do stuff when a is greater than b
}
else {
// do stuff when b is greater (or equal) to a
}
}
else {
// do stuff when the objects cannot be compared
}
Hope this helps
Joshua Flanagan
http://flimflan.com/blog