0

Here is sample code. How can I know both Foo and Bar are from same class Base<>?

class Program
{
    static void Main(string[] args)
    {
        var foo = typeof(Foo).IsAssignableFrom(typeof(Base<,>));
        var bar = typeof(Bar).IsAssignableFrom(typeof(Base<,>));
    }
}

public abstract class Base<TInput, TOutput>
{
    public abstract TOutput Run(TInput input);
}


public class Foo : Base<int, string>
{
    public override string Run(int input)
    {
        return input.ToString();
    }
}

public class Bar : Base<string, string>
{
    public override string Run(string input)
    {
        return input.Replace(".", "").ToString();
    }
}

enter image description here

Dongdong
  • 2,208
  • 19
  • 28

1 Answers1

1

To make your code compile you will need to change Base<> to Base<,> because it has two type parameters. Still IsAssignableFrom should not work cause, maybe something like this will work for you:

var foo = typeof(Foo).BaseType.GetGenericTypeDefinition() == (typeof(Base<,>));
var bar = typeof(Bar).BaseType.GetGenericTypeDefinition() == (typeof(Base<,>));

?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    @Dongdong you missed the `.BaseType.GetGenericTypeDefinition() == (typeof(Base<,>))` part =) – Guru Stron Jun 02 '20 at 15:17
  • 1
    @Dongdong glad it helped! But beware, it will work only for this hierarchy, if you introduce more levels of inheritance you will need to make more complicated checks. – Guru Stron Jun 02 '20 at 15:21
  • yes, you are right, just tried, how to resolve hierarchy issue? can you give more code for hierarchy? should I start a new question for it? – Dongdong Jun 02 '20 at 15:34
  • 1
    @Dongdong See [this](https://stackoverflow.com/questions/74616/how-to-detect-if-type-is-another-generic-type/1075059#1075059) as Stewart Ritchie suggested, so you basically need to check in cycle/via recursion for `BaseType` and check it against being generic and equal to searched type. – Guru Stron Jun 02 '20 at 15:37