Reputation: 10443
Not really sure about the is
keyword, but I think these two are the same. Can anyone confirm this?
public bool Equals(Object obj)
{
if (obj == null) return false;
MyType t = (MyType)obj;
if (t == null) return false;
return true;
}
and the other is...
public bool Equals(Object obj)
{
return obj is MyType;
}
Upvotes: 2
Views: 114
Reputation: 73311
An is expression evaluates to true if both of the following conditions are met:
expression is not null.
expression can be cast to type.
That is, a cast expression of the form (type)(expression) will complete without throwing an exception. For more information, see 7.6.6 Cast expressions. A compile-time warning will be issued if the expression expression is type is known to always be true or always be false.
The methods are not the same. If obj
is not of MyType
it will throw an exception while is
will not, it will return false
.
Upvotes: 1
Reputation: 941635
Not the same, the 1st version bombs with an InvalidCastException if an object of an unrelated type is passed.
Equals() is supposed to test for value equality, not type equality.
Upvotes: 1
Reputation: 55223
In the first method, you risk the cast failing and throwing an exception. I think you might be mixed up with the as
keyword, which returns null
if the cast fails instead. Once that's fixed, the methods would be roughly equivalent:
public bool Equals(Object obj)
{
return (obj as MyType) != null;
}
But the latter is more concise and clear anyway.
Upvotes: 2
Reputation: 244837
They are not the same. If obj
is not MyType
, the first version throws an exception, the second version returns false
.
And this implementation of Equals()
is quite strange. Are you sure you want to consider all instances of MyType
as equal?
Upvotes: 2
Reputation: 422026
No, they are definitely not equal. The cast to (MyType)
will throw InvalidCastException
immediately if obj
isn't an instance of MyType
. The expression will not evaluate to null
if the cast fails. as
operator exhibits the behavior you are expecting from that cast. My answer to another question discusses this in a bit more detail.
Upvotes: 4