Checking if the object is of same type

C#Object

C# Problem Overview


Hello I need to know how to check if the object of the same type in C#.

Scenario:

class Base_Data{}

class Person : Base_Data { }
class Phone  : Base_data { }

class AnotherClass
{
   public void CheckObject(Base_Data data)
   {
         if (data.Equals(Person.GetType()))
         { //<-- Visual Studio 2010 gives me error, says that I am using 'Person' is a type and not a variable.

        }
    }
}

C# Solutions


Solution 1 - C#

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 - C#

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.

Solution 3 - C#

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!

Solution 4 - C#

The intention of the question is a bit unclear but I found this question where looking for a way to check if 2 objects are of the same type. Here's my solution for that and some tests that all pass:

using NUnit.Framework;

[TestFixture]
public class TypeEqualityChecks
{
    class Base_Data { }

    class Person : Base_Data { }
    class Phone  : Base_Data { }

    class AnotherClass
    {
        public static bool CheckObjects(Base_Data d1, Base_Data d2) {
            return d1.GetType() == d2.GetType();
        }
    }
    
    [Test]
    public static void SameTypesAreEqual() {
        Base_Data person1 = new Person();
        Base_Data person2 = new Person();
        Assert.IsTrue(AnotherClass.CheckObjects(person1, person2));
    }
    
    [Test]
    public static void DifferentActualTypesAreNotEqual() {
        Base_Data person = new Person();
        Base_Data phone = new Phone();
        Assert.IsFalse(AnotherClass.CheckObjects(person, phone));
    }
    
    [Test]
    public static void BaseTypeAndChildTypeAreNotEqual() {
        Base_Data baseData = new Base_Data();
        Base_Data person = new Person();
        Assert.IsFalse(AnotherClass.CheckObjects(baseData, person));
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionslaoView Question on Stackoverflow
Solution 1 - C#Darin DimitrovView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#stakx - no longer contributingView Answer on Stackoverflow
Solution 4 - C#HemaolleView Answer on Stackoverflow