queryne
queryne

Reputation: 55

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?

Upvotes: 5

Views: 192

Answers (3)

Wer2
Wer2

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

erikH
erikH

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

Tejs
Tejs

Reputation: 41266

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.

Upvotes: 4

Related Questions