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?
JavaScript type checking is not as strict as other programming languages. Use the typeof operator for detecting types.
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...
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.
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.
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)))
{
}
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