Checking if the object is of same type
Solution 1:
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`.
}
Solution 2:
It depends on exactly what you're after. Using is
or as
(as shown in Darin's answer) will tell you if data
refers to an instance of Person
or a subtype. That's the most common form (although if you can design away from needing it, that would be even better) - and if that's what you need, Darin's answer is the approach to use.
However, if you need an exact match - if you don't want to take the particular action if data
refers to an instance of some class derived from Person
, only for Person
itself, you'll need something like this:
if (data.GetType() == typeof(Person))
This is relatively rare - and it's definitely worth questioning your design at this point.