Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the "is" keyword work?

More specifically, why does this work:

foreach (ChangeSetEntry changeRow in changeSet.ChangeSetEntries)
    if (changeRow is RouteStage)
    { ... }

but this not?

ChangeSetEntry changeRow = changeSet.ChangeSetEntries[0];
if (changeRow is RouteStage)
{ ... }

In the latter case, I get a compiler warning saying:

The given expression is never of the provided type.

I can understand that, as changeRow is a ChangeSetEntry not a RouteStage, so why does it work inside the foreach block?

This is in my override of the Submit method in an RIA Services DomainService. RouteStage is an entity I have defined to be returned by the DomainService.

like image 340
john_cat Avatar asked Jan 02 '14 16:01

john_cat


People also ask

Is vs AS keyword?

The is operator returns true if the given object is of the same type, whereas the as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type, whereas the as operator returns null if the conversion is not possible.

Is and as in C# example?

The is operator returns false if the given object is not of the same type whereas as operator return null if the conversion is not possible. The is operator is used for only reference, boxing, and unboxing conversions whereas as operator is used only for nullable, reference and boxing conversions.

Is operator a keyword in C#?

The operator keyword is used for overloading binary and unary operators. We provided an example of operator overloading. We saw a list of all the overloadable C# operators.

Is operator null C#?

operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-hand operand.


1 Answers

I tested your code examples (exact same conditions you described, in the Submit override of a RIA domain service), both are producing a warning.

It's actually expected: in both cases you have changeRow that is declared as a ChangeSetEntry variable. Whether it's in a foreach loop or not doesn't change anything about that. And as RouteStage doesn't inherit from ChangeSetEntry (which is sealed), the warning should always be displayed.

Either you oversimplified your example (and something is missing), or as Jon Skeet suspected, the RouteStage type in both code snippets doesn't actually refer to the same type (check you don't have using RouteStage = ChangeSetEntry; somewhere in your class).

like image 94
ken2k Avatar answered Oct 14 '22 14:10

ken2k