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
.
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.
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.
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.
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.
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).
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