If the as
operator in C# can only be used with reference and nullable types, is the same is valid for is
operator?
Not entirely. The is
operation can be used against any type, since you can always check type equality with any type. It's semantically the same as
if(someVariable.GetType().IsAssignableFrom(anotherVariable.GetType()))
You can view the documentation about this here.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With