Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

You can check class using GetType method.

if (!illnesses.Any(i => i.GetType() == illness.GetType()))
{
   illnesses.Add(illness);
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!