0

I have a set of classes that use generics and generic constraints fairly heavily and I have hit an issue, while not a show stopper, makes the code quite cumbersome. I get an issue where the compiler is telling me it cannot convert a one parameter to another type when the two are related

I have created a simplified repro below

class Foo
{

}

class Quux<TFoo> : Bar where TFoo : Foo 
{
    public Quux(Spong<Bar> spong)
    {

    }    
}

class Baz : Quux<Foo>
{
    public Baz(Spong<Baz> bf) : base(bf)
    {

    }
}


class Spong<TBar> where TBar : Bar
{
}


class Bar
{

}

It is the constructor of Baz that has the issue where forwarding to the base class has the following compiler error

CS1503  Argument 1: cannot convert from 'TestGenericWeirdness.Spong<TestGenericWeirdness.Baz>' to 'TestGenericWeirdness.Spong<TestGenericWeirdness.Bar>'    

When these two types are clearly related via Quux

Only by changing the code to

public Baz(Spong<Bar> bf) : base(bf)
{            
}

Does the error go away. Now you may say "Its really not that big a deal" but the real code is integrating with Aspnet.Identity and has 8 not 1 generic arguments that would have to be fully specified

Anyone know what the issue is and / or a workaround?

Richard Blewett
  • 6,089
  • 1
  • 18
  • 23
  • 2
    Basically the same as https://stackoverflow.com/q/16966961/993547. – Patrick Hofman Dec 13 '17 at 09:28
  • Ah yes I see it now assumed it was probably a co/contra variance thing but couldn't see the problem. Unfortunately I cannot change to working with interfaces due to Aspnet.Identity so I'm hosed - thanks – Richard Blewett Dec 13 '17 at 09:33
  • @PatrickHofman why not close as duplicate? – Zohar Peled Dec 13 '17 at 09:48
  • Because I have had a few cases the last days where my closed questions were reopened because they didn't fit the full 100%. @ZoharPeled – Patrick Hofman Dec 13 '17 at 09:55
  • IMHO only rare cases are a 100% fit, However that doesn't mean it's not a duplicate. I've even marked and saw other people mark duplicates where the question was completely different and yet the answer solved both questions.... – Zohar Peled Dec 13 '17 at 09:58

0 Answers0