makoshichi
makoshichi

Reputation: 2390

Get a List<Type> of all derived types in a list of objects that inherit from an abstract class

I've seen a bunch of questions dealing with getting all types from a base type and so on, but that's not quite what I need. For instance, I have and abstract base class:

public abstract class BasePart
{
    //whatever 
}

And I have a bunch of classes that derive from it. Like...

public class HorizontalPanel : BasePart { //code }
public class VerticalPanel : BasePart { //code }
public class RainBoard : BasePart { //code }

And so on. I always list them by the base class:

List<BasePart> parts;

And I use typecasting and generics to do whatever I want with them. However, I came to a point where I need to filter this list and I only want the type information available in it. And only once for type. For instance, if my list has three HorizontalPanels and two VerticalPanels, what I want from it is a List<Type> that only contains {HorizontalPanel, VerticalPanel}. I suppose I can mess around with the objects themselves in chained loops to get what I want, but I'm positive that C# has a better way to do it. Anyone?

Upvotes: 0

Views: 1644

Answers (2)

RenanB
RenanB

Reputation: 105

You can use Object.GetType() to retrieve the type of the object and populate a list.

Afterwards, since you need a list which contains only one instance of each type, you can call Enumerable.Distinct() on the list you populated previously, and Enumerable.ToList() to convert the resulting enumerable to a list.

All in all, the code will be something akin to:

List<Type> types = new List<Types>();

foreach (Base element in MyList){
    types.add(element.GetType());
};

List<Type> unique_types = types.Distinct().ToList();

Which will give you the list unique_types filled with exactly one instance of each type present in MyList.

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249486

There is no language feature to help you with this. The simplest way would be to use LINQ, first use Select to get all the types and use Distinct

parts.Select(x => x.GetType()).Distinct();

Upvotes: 5

Related Questions