Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The "is" and "as" operators in C#

If the as operator in C# can only be used with reference and nullable types, is the same is valid for is operator?

like image 234
queryne Avatar asked Aug 24 '11 19:08

queryne


2 Answers

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.

like image 86
Tejs Avatar answered Nov 07 '22 08:11

Tejs


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.

like image 24
Wer2 Avatar answered Nov 07 '22 10:11

Wer2