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`.
}
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.
Let's fix this one step at a time. The first step is required, the next two are optional but suggested.
The first correction (which is required) makes sure that you're not comparing an object of some type with an object of type System.Type
:
if (data.GetType().Equals(typeof(Person))) ...
// ^^^^^^^^^^
// add this to make sure you're comparing Type against Type, not
// Base_Data against Type (which caused the type-check error)!
Second, simplify this to:
if (data is Person) ... // this has (almost) the same meaning as the above;
// in your case, it's what you need.
Third, get rid of the if
statement altogether! This is done by employing polymorphism (or, more precisely, method overriding) e.g. as follows:
class Base_Data
{
public virtual void Check() { ... }
}
class Person : Base_Data
{
public override void Check()
{
... // <-- do whatever you would have done inside the if block
}
}
class AnotherClass
{
public void CheckData(Base_Data data)
{
data.Check();
}
}
As you see, the conditional code has been shifted into a Check
method of the Base_Data
class and its derived class Person
. No more need of such a type-checking if
statement!