Checking if the object is of same type

You could use the is operator:

if (data is Person)
{
    // `data` is an instance of Person
}

Another possibility is to use the as operator:

var person = data as Person;
if (person != null)
{
    // safely use `person` here
}

Or, starting with C# 7, use a pattern-matching form of the is operator that combines the above two:

if (data is Person person)
{
    // `data` is an instance of Person,
    // and you can use it as such through `person`.
}

Leave a Comment