dev hedgehog
dev hedgehog

Reputation: 8791

Compare without generics

I have a bit complicated issue to solve.

I have a list of objects though later the list will be filled with two different type of instances.

First type is MyFirstType<T1, T2> and second type is MySecondType<T>

Now I need to run though the list of objects and ask which one of the two is each item. Then I need to do some custom logic on the item.

For example:

foreach(object obj in list)
{
   if(obj is MyFirstType<T1, T2>)
   {
     // do something
   }
   else if(obj is MySecondType<...>)
   {
   }
}

The problem is T or T1 and T2 could be any types so how do I write such an if - Is Keyword statement that only comparies if MyFirstType but not the generics inside? if(obj is MyFirstType<T1, T2>) does not work since it needs concrete types for T1 and T2.

Like mentioned just need comparison without T1 and T2. Any ideas how to solve this?

Upvotes: 0

Views: 93

Answers (3)

Ben
Ben

Reputation: 645

Why don't you use polymorphism? Have the two types implement an interface with a common method. Then in the implementation of each type write the code for the method you need.

public interface ICommon
{
    void DoThis();
}

For MyFirstType and MySecondType you will have:

public class MyFirstType<T> : ICommon
{
    public void DoThis()
    {
        //DoThis
    }
}

public class MySecondType<T1,T2> : ICommon
{
    public void DoThis()
    {
        //DoThis
    }
}

Then you could write the following foreach loop:

foreach(object obj in list)
{
    obj.DoThis();
}

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 156968

  1. The cheap solution: create a flag interface which you derive in your types. This is just a helper to determine the type.
  2. Use reflection and check the type definition and check the name of the type.

Upvotes: 3

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

You can use IsGenericType property of Type class to check if obj.GetType() is generic, and then use GetGenericTypeDefinition to get generic type definition, which can be compared to typeof(MyFirstType<,>) and typeof(MySecondType<>):

foreach(object obj in list)
{
    if(obj.GetType().IsGenericType)
    {
        if(obj.GetType().GetGenericTypeDefinition() == typeof(MyFirstType<,>))
        {
          // do something
        }
        else if(obj.GetGenericTypeDefinition() == typeof(MySecondType<>))
        {
        }
    }
}

Upvotes: 2

Related Questions