Question

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.

Was it helpful?

Solution 2

The line should read:

if (changeRow.Entity is RouteStage)

...then it compiles cleanly. One of those cases of "can't see for looking". TFS highlighted what I had inadvertently changed.

OTHER TIPS

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

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

I don't think that it works in foreach loop. The only difference seems to be that compiler doesn't perform static check on variables inside the loop. Hence, no warning displayed. But I suppose that execution never passes if within the foreach loop because the condition is always false.

Way out of this is just to remove the if statement in both forms, because it is known in advance to never be true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top