3

The code below is just an example

// error CS0305
AddList<IntList>();

// no errors, but specifying T is clearly redundant 
// because compiler already knows that IntList is derived from List<int>
AddList<IntList, int>();

void AddList<TList, T>() where TList : List<T>
{
    // ...
}

class IntList : List<int> { }

Is there any way to write AddList<IntList>(); instead of AddList<IntList, int>();?


Edit: I think I should use other example, because inheritance from List creates confusion

CreateGeneric<DerivedGeneric>(); // error
CreateGeneric<DerivedGeneric, int>(); // no error

TGeneric CreateGeneric<TGeneric, T>() where TGeneric : Generic<T>, new()
{
    return new TGeneric();
}

class DerivedGeneric : Generic<int> { }
class Generic<T> { }
Nebulaxin
  • 39
  • 2
  • 2
    How about `void AddList>(T item)`? The call would be `var number = 5; AddList(number);`. Or give a more complete example that also shows how the method should be used. – Oliver Feb 27 '23 at 15:00
  • 1
    Is that really a _parameterless_ `AddList()`? Looks suspicious to me: should have at least 1 argument, shouldn't it? – Fildor Feb 27 '23 at 15:04
  • c# Does not do partial type inference. In some cases it is possible to do a workaround with a helper type, or just not use generics. But without a real example it is difficult to provide any recommended workaround. – JonasH Feb 27 '23 at 15:05
  • @Oliver, I think I should have used `class Generic { }` and `class DerivedGeneric : Generic` in example instead of `class IntList : List` – Nebulaxin Feb 27 '23 at 15:18
  • 1
    Could you please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) to avoid guessing game? – Peter Csala Feb 27 '23 at 15:26
  • 2
    Still not a good example as it does not need T in the first place. Now the guessing goes just in a different direction. – Ralf Feb 27 '23 at 15:39

1 Answers1

0

Since you have dependencies on two separate types, there is no way for the compiler to infer the relationship without passing both types for verification.

If you find yourself writing this type of code often, you can always wrap the common methods in a typed class that abstracts away type T.

public class GenericHelper<T> where T : new()
{
    public TGeneric CreateGeneric<TGeneric>() where TGeneric : Generic<T>, new()
    {
        return new TGeneric();
    }
}

This allows the following:

var helper = new GenericHelper<int>();
helper.CreateGeneric<DerivedGeneric>();

to be called without error.

David L
  • 32,885
  • 8
  • 62
  • 93