By Interface
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
object[] items = { new Person(), new Human() };
foreach (var item in items)
{
if (item is IBase)
{
Console.WriteLine(item.GetType());
}
}
Console.ReadLine();
}
}
public interface IBase
{
public int Id { get; }
}
public class Person : IBase
{
public int Identifier { get; set; }
public int Id => Identifier;
}
public class Human
{
public int Identifier { get; set; }
}
}
C#9 or higher
class Program
{
static void Main(string[] args)
{
object[] items = { new Person() {Identifier = 3}, new Human() };
foreach (var item in items)
{
if (item as IBase is { } casted)
{
Console.WriteLine(casted.Id);
}
}
Console.ReadLine();
}
}
And for types
static class Extensions
{
public static bool Implements<I>(this Type source) where I : class
=> typeof(I).IsAssignableFrom(source);
}
Usage
static void Main(string[] args)
{
IEnumerable<Type> result = TypesList().Where(type => type.Implements<IBase>());
}
private static object[] TypesArray()
{
object[] items = { new Person() { Identifier = 3 }, new Human() { Identifier = 2 } };
return items;
}