How to check if an object is not of a particular type?
Extensions methods to the rescue!!
public static class ObjectExtensions
{
public static bool Isnt(this object source, Type targetType)
{
return source.GetType() != targetType;
}
}
Usage
if (t.Isnt(typeof(TypeA)))
{
...
}
If you are doing a TypeA x = (TypeA)t;
inside the if block then a better way is
TypeA x = t as TypeA
if(x != null)
{
...
}
This causes only one time type checking rather than twice.
UPDATE 2020-10-30:
Times are changing. Starting from C# 9.0 you can use more natural way of checking it:
if(t is not TypeA) { ... }
ORIGINAL ANSWER:
C# is not quite natural language ;) Use this one
if(!(t is TypeA))
{
...
}
if you want not only check, you can use as operator.
var a = t as TypeA;
if(a!= null)
//use a..
In this way, if you want use a type after check, you avoid double casting..