I have a problem where I need to compare two objects but of course you can't do this with ordinary objects. I figure I need to cast the objects to their respective types first and then compare them. I don't really know what the object types will be so I can't just tell myself in code. Really, it seems like I need a cast function that I can pass the object type into and have it cast the object. Here is a code-snipit:
I've constrained the above method to work only from types derived from Tbase (which you'll have to define). You also need to implement the IComparable in Tbase and override the CompareTo() method in each derived class. I don't expect the code snippet above to work right out of the box, but hopefully it will give you some ideas.
I have a problem where I need to compare two objects
The solution is simples!
Code:
object first = GetFirstObject ();
object second = GetSecondObject ();
if (first is IComparable)
return ((IComparable) first).CompareTo (second) < 0;
If you know what type they are supposed to be you could also check for the generic IComparable<T> interface and potentially use that, but the non-generic one is probably your best bet.
If the objects don't support the IComparable interface the only way to use '>' or '<' to compare the items is to actually cast them in code to the correct type as follows:
Code:
object first = GetFirstObject ();
object second = GetSecondObject ();
if (first is MyClass && second is MyClass)
return (MyClass)first < (MyClass) second;
else
throw new Exception ("Cannot compare");
NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
The problem with using typeof, ChangeType and anything else like that is that this type that I'm trying to cast my objects to is unknown at compile time. It is not declared anywhere in my project so I cannot cast it using the normal means. I found an article on DynamicCasting using Reflection but even that doesn't help because I don't have the actual type of the object to cast it to. I have the Type, but that is different from having the type declared in my code. I'm wondering if the only solution is to force all objects to have a base type that they are derived from so at least I have something to cast them to. Otherwise, there seems to be no way I can do this in C#. Am I wrong?
Bookmarks