5
return (
      Page is WebAdminPriceRanges ||
      Page is WebAdminRatingQuestions
);

Is there a way to do it like:

return (
    Page is WebAdminPriceRanges || WebAdminRatingQuestions
);
Tudor
  • 61,523
  • 12
  • 102
  • 142
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
  • I don't think it is possible, and it's meaningless. –  May 23 '12 at 08:39
  • 1
    The is operator takes two operands in C#. That is really all there is to say. However, with a bit of fancy, "could be" similar to `IsAnyOf(x, myListOfTypes)` (it would use `IsAssignableFrom` internally though, not `is`.) In fact, I have seen this done before on SO. (Try searching for `IsAssingableFrom`.) –  May 23 '12 at 08:40
  • e.g. http://stackoverflow.com/questions/3013694/use-of-isassignablefrom-and-is-keyword-in-c-sharp –  May 23 '12 at 08:42

6 Answers6

4

No, such syntax is not possible. The is operator requires 2 operands, the first is an instance of an object and the second is a type.

You could use GetType():

return new[] { typeof(WebAdminPriceRanges), typeof(WebAdminRatingQuestions) }.Contains(Page.GetType());
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
4

Not really. You can look for the Type instance inside a collection, but that doesn't account for the implicit conversions that is performs; for example, is also detects if the type is a base of the instance it operates on.

Example:

var types = new[] {typeof(WebAdminPriceRanges), typeof(WebAdminRatingQuestions)};

// this will return false if Page is e.g. a WebAdminBase
var is1 = types.Any(t => t == Page.GetType());

// while this will return true
var is2 = Page is WebAdminPriceRanges || Page is WebAdminRatingQuestions;
Jon
  • 428,835
  • 81
  • 738
  • 806
2

No. The first way you specified is the only reasonable way to do this.

tomfanning
  • 9,552
  • 4
  • 50
  • 78
1

No, C# is not the English language, you cannot omit one operand from a two-operand operation.

Tudor
  • 61,523
  • 12
  • 102
  • 142
0

No, you can not do this.

if your intent is return a Page, only if it is of type WebAdminPriceRanges or WebAdminRatingQuestions , you can easily do it with if.

For example:

if(Page is WebAdminPriceRanges || Page is WebAdminRatingQuestions)
   return Page;
return null;

Assuming that Page is a reference type or at least nullable value type

Tigran
  • 61,654
  • 8
  • 86
  • 123
0

The other answers are true, but while I'm not sure where is fits in operator precedence. If the is operator is lower than the logical-or operator, you would be or-ing two classes together which is meaningless.

kenny
  • 21,522
  • 8
  • 49
  • 87