Reputation: 87
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'"
Upvotes: 0
Views: 298
Reputation: 149538
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.
Upvotes: 3
Reputation: 31116
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.
Upvotes: 1
Reputation: 174329
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.
Upvotes: 0