'How to check if a list contains specific class in C#

Several classes inherit from abstract class Illness and overrides a field name
Illness.cs:

namespace health;
abstract class Illness{
    public abstract string name { get;}
}

class Cancer : Illness{
    public override string name { 
        get{ return "Cancer";}
    }
}

class Covid : Illness{
    public override string name { 
        get{ return "Covid";}
    }
}

There is an empty list List<Illness> illnesses = new List<Illness> in main class and the goal is to make a method, which adds a value to illnesses list only if this list doesn't contain the given class already.
Tried to do this:

public void addIllness(Illness illness){
        if (!illnesses.Contains(illness)){
            illnesses.Add(illness);
        }
    }

but not working.



Solution 1:[1]

You can (as mentioned by Lei Yang) solve this by checking he type:

  • if(!illnesses.Any(i=>i is typeof(Covid)){ ... } for a specific type.
  • if (!illnesses.Any(i => i.GetType() == illness.GetType())) { ... } comparing the type of the objects.

You could also create a generic method to achieve this in a nice manner:

public void Add<T>(T illness) where T : Illness{
    if(!illnesses.Any(t=>t is T)){
        illnesses.Add(illness);
    }
}

As you are overriding name you could even use that for better performance:

if(!illnesses.Any(i=>i.name == illness.name)){ ... } This is however more or less the explicit version of what (again) @Lei Yang proposed in implementing IEquatable.

This however seems to be a bit strange of an approach, you should use objects when you can have more than one instance of a class, else maybe reconsider adding a "IllnessType" enum beside the Name and ditch the inheritance.

Solution 2:[2]

You can check class using GetType method.

if (!illnesses.Any(i => i.GetType() == illness.GetType()))
{
   illnesses.Add(illness);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Stanislav Tarasov