How test if System.Object's are same type and equal?

E

Ed Sutton

I have variables that are declared as objects. Ints, strings and other data
types are then assigned to these objects.

How can I write a compare objects function? I tried objOne==objTwo. I am
guessing that this must be comparing references and not values because it
returns false.

// Test case
objOne = strName1;
objTwo = strName2;
if( CompareObjects(objOne,objTwo) == true)
{
WriteLine("Objects are of same type and equal");
}

// Object Compare function
bool CompareObjects(object objOne, object objTwo)
{
bool bCompareResult = false;
if( objOne == objTwo)
{
bCompareResult = true;
}
return bCompareResult;
}


I have started down the path of using System.Type.GetTypeCode of the
object's type and then making a big hairy switch statement that casts each
object to the appropriate type before making the comparison. Something
like..

switch( System.Type.GetTypeCode(objOne.GetType()))
{
case System.TypeCode.Int32:
bCompareResult = (int)objOne== (int)objTwo;
break;
case System.TypeCode.String:
bCompareResult = (string)objOne== (string)objTwo;
break;
 
S

Santastp

Check in the document of .NET.
You have example for keyword [is], [typeof], and [as]
Maybe some of these keyword can give you a help!

Stephane
 

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