Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"is" - operator for Type

I use the "is" operator to find a certain class:

for(int i=0; i<screens.Count; i++){
  if(screen is ScreenBase){
    //do something...
  }
}

This works fine especially as it finds any class that inherits from the ScreenBase but not the base classes from ScreenBase.

I would like to do the same when I know only the Type and don't want to instantiate the class:

Type screenType = GetType(line);
if (screenType is ScreenBase)

But this comparsion produces a warning as it will compare to the "Type" class.

The only alternative I know would be to compare with ==typeof but this would test only for the exact type and not the inherited ones. Is there a way to get a similar behaviour like the "is" operator but for the type described by the Type-class?

like image 745
michael Avatar asked Sep 18 '11 19:09

michael


People also ask

Which operator is used for type checking?

JavaScript type checking is not as strict as other programming languages. Use the typeof operator for detecting types.

Is operator a syntax?

The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons. If object1 and object2 both refer to the exact same object instance, result is True ; if they do not, result is False . The Is keyword is also used in the Select...

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.

IS NOT NULL in C#?

NotNull: A nullable field, parameter, property, or return value will never be null. MaybeNullWhen: A non-nullable argument may be null when the method returns the specified bool value. NotNullWhen: A nullable argument won't be null when the method returns the specified bool value.


1 Answers

The only alternative I know would be to compare with ==typeof but this would test only for the exact type and not the inherited ones. Is there a way to get a similar behaviour like the "is" operator but for the type described by the Type-class?

If GetType(line) returns a type (I'd recommend a better name for that, btw), you can use Type.IsAssignableFrom:

if (typeof(ScreenBase).IsAssignableFrom(GetType(line)))
{
}
like image 69
Reed Copsey Avatar answered Oct 20 '22 16:10

Reed Copsey