0

Here's a simplified example that doesn't compile.

public class T1Class
{
}
public class Test<T> where T : T1Class
{
    public Test(IRepository repository)
    {
        repository.SavingT1Class(this);

    }
}
public interface IRepository
{
    void SavingT1Class(Test<T1Class> test);
}

I find it strange that the compiler cannot infer that the Test< T> class that I'm sending into SavingT1Class(Test< T1Class> test) is actually Test< T1Class> because I've defined T as T1Class. And cannot "convert" the T into TClass.

Any Ideas how I can make the compiler understand that 'this' is actually Test< T1Class> without adding generics to IRepository itself?

  • If `T` is a subclass of `T1Class`, then it would be invalid to pass that `Test` to the `SavingT1Class` method. – Johnathan Barclay Mar 03 '22 at 09:16
  • Have you tried `void SavingT1Class(Test test) where T: T1Class;` ? – Fildor Mar 03 '22 at 09:39
  • @JohnathanBarclay. Huh that's correct. I assumed that would be valid, in the same way that sending subclass of a parameter is allowed. That would explain it. Though I cannot understand why it sending SubClass would work but Test wouldn't. – Ashlander Mar 03 '22 at 09:40
  • 2
    That's because even if `T` "is-a" `T1Class`, that doesn't make `Test` "is-a" `Test`. The latter two are completey unrelated inheritance-wise. – Fildor Mar 03 '22 at 09:42
  • @Fildor Yeah that would work, but in my case (not in the simplified example in the post) would add a lot of noise in the code that is used in tons of places. Since there are a lot of methods in IRepository that would need to have that and those used in many places so I'm hoping there's a more clean way. – Ashlander Mar 03 '22 at 09:44
  • 2
    [Covariance and Contravariance in Generics](https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance). – Johnathan Barclay Mar 03 '22 at 09:44
  • @Fildor I don't see why it doesn't make Test a Test because I've defined T as T1Class, thus Test must be Test? – Ashlander Mar 03 '22 at 09:45
  • That's exactly the pitfall most people (including me) fall into, when starting out with Generics. No, Test is not a Test. See Johnathan's link. Read it carefully and make sure you understand. I regularly revisit that section ;D – Fildor Mar 03 '22 at 09:47
  • 1
    @JohnathanBarclay Thanks for that link. That looks to cover my misunderstanding, going to read through that. – Ashlander Mar 03 '22 at 09:48
  • 1
    @Fildor Hehe, I see. I've certainly fallen in that pitfall, will read through it. – Ashlander Mar 03 '22 at 09:48
  • 1
    Using a `Test` in place of a `Test` would break type-safety. [Here is an example why](https://stackoverflow.com/a/69673580/8126362). – Johnathan Barclay Mar 03 '22 at 09:49

0 Answers0