0

Hi I was curious if there's an easy way to retrieve nested generics from a given type. For example say I have:

public class Token<T, V>
{
    protected readonly T fieldT;
    protected readonly V fieldV;

    public Token(T arg1, V arg2)
    {
        fieldT = arg1;
        fieldV = arg2;
    }
}

public abstract class TokenBuilder<TokenType, T, V>
    where TokenType: Token<T, V>
{
    public abstract TokenType CreateToken(T arg1, V arg2);
}

This works well enough with subclassing. However when T, V are complex I'd prefer to infer them. For example

// T is a tuple (int num1, int num2, int num3, int num4)
// V is a tuple (string name1, string name2, string name3)

public class FancyToken : Token<
    (int num1, int num2, int num3, int num4),
    (string name1, string name2, string name3)
>
{
    protected readonly (int num1, int num2, int num3, int num4) fieldT;
    protected readonly (string name1, string name2, string name3) fieldV;

    public Token(
        (int num1, int num2, int num3, int num4) arg1,
        (string name1, string name2, string name3) arg2
    )
    {
        fieldT = arg1;
        fieldV = arg2;
    }
}
// All of this is fine!

// Do I have to redeclare <T, V> here? Shouldn't they be inferred from FancyToken?
public class FancyTokenBuilder : TokenBuilder<FancyToken, (int num1, int num2, int num3, int num4), (string name1, string name2, string name3)>
{
    public FancyToken CreateToken((int num1, int num2, int num3, int num4) arg1, (string name1, string name2, string name3) arg2){
        ...
    }
}

This is fairly minor, but I'm basically curious if the generic arguments supplied to FancyToken (T, V) can be "pulled out" and used by another class that takes in a Token as a parameter. Redeclaring these T, V explicitly works perfectly, but I'm curious if there's any way around re-writing those types again

Ian
  • 301
  • 3
  • 6
  • What you are asking for is basically that the compiler should infer the types based on the generic constraint you have. This is not possible, and there are a bunch of existing questions on the topic. For example https://stackoverflow.com/questions/4477636/why-must-i-provide-explicitly-generic-parameter-types-while-the-compiler-should – JonasH Dec 15 '20 at 12:32
  • Thank you so much! I didn't know quite how to phrase this question, and this absolutely answers my question. – Ian Dec 15 '20 at 13:54

0 Answers0