Reputation: 55
If the as
operator in C# can only be used with reference and nullable types, is the same is valid for is
operator?
Upvotes: 5
Views: 192
Reputation: 86
It becomes more clear when you think about how "as" would be implemented. If "as" was a function:
public T as<T>(object obj){
if(obj is T)
{
return (T) obj;
}
else
{
return null;
}
}
As this shows, T has to be a Nullable or a reference type because otherwise there would be no way to return null.
The "is" operator does no suffer from this problem because it returns a boolean and thus does not have to worry about if the target can be represented as null.
Upvotes: 3
Reputation: 2346
It can be used with any type, since "is" considers boxing/unboxing.
int test = 4;
object test2 = test;
bool isTrue = (test2 is int);
Upvotes: 0