To create a collection of types, use typeof()
:
new[] { typeof(Class1), typeof(Class2), typeof(Class3) }
This creates a Type[]
. However, is
can't be used on Type
instances. You can use IsAssignableFrom
instead. Note that just comparing if the type of item
is equal to the array elements is not enough to replicate the behaviour of is
- is
does more than that. It checks the inheritance hierarchy, and a bunch of other stuff too.
Combine that with Any
, you get:
if (new[] { typeof(Class1), typeof(Class2), typeof(Class3) }.Any(x => item.GetType().IsAssignableFrom(x))) {
}
This certainly doesn't look too much more elegant than your original, but if you have a lot of types to check, it will eventually be shorter.
Note that unless all the types have some common members, checking whether an object is
any of those types isn't very useful. There isn't anything extra that you suddenly can now do, once you know that item
is one of these types. You still can't safely cast it to a specific type.
If all the types do have some common members, consider writing an interface with all the common members, and making those types implement that interface. This way you just need to check if item is
that interface!