Although this seems like something that should be painfully obvious, the method eludes me...
I need to cast an object to a specific System.Type object. It's more clear in code:
...
int a = 1;
int b = 1;
Compare(a,b,typeof(int));
...
public bool Compare(object intA, object intB, Type type)
{
return (intA == intB); //returns false
}
How do I cast intA and intB to integers without doing so explicitly I need to cast them using the System.Type object, since it is unknown within Compare that these are int types.

Casting an object to a specified System.Type object
DustyBottoms
Hi,
The objects that you send as parameter are keeping their types (upon you have objects, if you do typeof you will get the original type). I suggest to follow the microsoft approach, using polimorphism like
public bool Compare (int x, int y) { return x.CompareTo(y) == 0; }
public bool Compare (string x, string y) { return x.CompareTo(y) == 0; }
or use CompareTo directly if it is possible (it will be faster)
Cheers
papadi
If you are using .NET 2 you can use the generic Comparer<T> to perform the comparison.
Thomas.Goddard
Of course that is working; just try it - is just one line Console.WriteLine(((object)1).Equals((object)1));
Paulyz
Try
public bool Compare(object intA, object intB)
{
return intA.Equals(intB);
}
Try to read a little bit about == operator, Equals, ReferenceEquals; The differences between these when applying to references or value types;
Generics will also help you implement situations similar with this one.
CarlosSantamaria
I was looking at his comparer method which used == instead of Object.Equals. Using .Equals returns true, using == does not.
.NETPhreak
In other words, I have an object objA.
And I have a Type typeObjA which is the Type of objA.
Is there anyway to cast objA to this type