Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"is" c# multiple options

Tags:

c#

c#-4.0

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

Is there a way to do it like:

return (
    Page is WebAdminPriceRanges || WebAdminRatingQuestions
);
like image 650
Mosh Feu Avatar asked May 23 '12 08:05

Mosh Feu


2 Answers

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());
like image 72
Darin Dimitrov Avatar answered Oct 22 '22 16:10

Darin Dimitrov


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;
like image 30
Jon Avatar answered Oct 22 '22 17:10

Jon