简体   繁体   中英

Custom Equals Method in C#

I wrote a class called baseCommodity and it includes a customized Equals method:

public override bool Equals(object obj)
{
    BaseCommodity other = obj as BaseCommodity;
    return other != null && other.GetType() is this.GetType());
}

I want to compare the other.GetType() with the Type of this class but is this.GetType() does not work. I keep getting the error "Unexpected symbol this', expecting type'"

You want == instead:

return other != null && other.GetType() == this.GetType();

You can use is when the you know the compile time type token of the object which you can check against.

As a side note, if you're overriding Equals(object other) , perhaps you also want to implement IEquatable<BaseCommodity> and override it's Equals(BaseCommodity other) which saves you the type checking.

Also, this is a very weak type equality check.

Perhaps a bit more info would be nice for an answer.

GetType returns a type object , not a type token . Type tokens are handled with is , type objects are compared using equality (==).

In other words:

object a = 12893;
if (a is int) // compare by token:
{ ... }

and

object a = 12345;
if (a.GetType() == typeof(int)) // compare by equality of type object.
{ ... }

PS: Equality can give strange results with inheritance. In this case you might want to use SomeType.IsAssignableFrom instead.

As others have stated, you need the comparison operator == here.

is is a type check and it is used with a variable on the left and a type on the right:

string s = "";
bool isString = s is string;

Please note that the result of GetType is not a type , it is a variable that represents a type .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM