<p>I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation.  Ideally I would like to do something like the following:</p>

<pre><code>abstract class Animal
{
  public Leg GetLeg() {...}
}

abstract class Leg { }

class Dog : Animal
{
  public override DogLeg Leg() {...}
}

class DogLeg : Leg { }
</code></pre>

<p>This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs.  The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg.  I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#.</p>

<p><strong>EDIT</strong>: I modified this somewhat, since I'm actually using properties instead of functions in my code.  </p>

<p><strong>EDIT</strong>: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function <strong>shouldn't</strong> work).  Sorry for the fluctuations!  I realize it makes a lot of the answers seem irrelevant.</p>

[{'answer_id': 46935, 'author': 'shsteimer', 'author_id': 292, 'author_profile': 'https://Stackoverflow.com/users/292', 'pm_score': 2, 'selected': False, 'text': '<p>GetLeg() must return Leg to be an override.  Your Dog class however, can still return DogLeg objects since they are a child class of Leg.  clients can then cast and operate on them as doglegs.</p>\n\n<pre><code>public class ClientObj{\n    public void doStuff(){\n    Animal a=getAnimal();\n    if(a is Dog){\n       DogLeg dl = (DogLeg)a.GetLeg();\n    }\n  }\n}\n</code></pre>\n'}, {'answer_id': 46940, 'author': 'Brian Leahy', 'author_id': 580, 'author_profile': 'https://Stackoverflow.com/users/580', 'pm_score': 3, 'selected': False, 'text': "<p>Dog should return a Leg not a DogLeg as the return type.  The actual class may be a DogLeg, but the point is to decouple so the user of Dog doesn't have to know about DogLegs, they only need to know about Legs.</p>\n\n<p>Change:</p>\n\n<pre><code>class Dog : Animal\n{\n  public override DogLeg GetLeg() {...}\n}\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>class Dog : Animal\n{\n  public override Leg GetLeg() {...}\n}\n</code></pre>\n\n<p>Don't Do this:</p>\n\n<pre><code> if(a instanceof Dog){\n       DogLeg dl = (DogLeg)a.GetLeg();\n</code></pre>\n\n<p>it defeats the purpose of programing to the abstract type.</p>\n\n<p>The reason to hide DogLeg is because the GetLeg function in the abstract class returns an Abstract Leg. If you are overriding the GetLeg you must return a Leg.  Thats the point of having a method in an abstract class.  To propagate that method to it's childern.   If you want the users of the Dog to know about DogLegs make a method called GetDogLeg and return a DogLeg.</p>\n\n<p>If you COULD do as the question asker wants to, then every user of Animal would need to know about ALL animals.</p>\n"}, {'answer_id': 46942, 'author': 'Luke', 'author_id': 327, 'author_profile': 'https://Stackoverflow.com/users/327', 'pm_score': 0, 'selected': False, 'text': "<p>Right, I understand that I can just cast, but that means the client has to know that Dogs have DogLegs.  What I'm wondering is if there are technical reasons why this isn't possible, given that an implicit conversion exists.</p>\n"}, {'answer_id': 46946, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 5, 'selected': True, 'text': '<p>The short answer is that GetLeg is invariant in its return type. The long answer can be found here: <a href="http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx" rel="noreferrer">Covariance and contravariance</a></p>\n\n<p>I\'d like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers.</p>\n'}, {'answer_id': 46950, 'author': 'shsteimer', 'author_id': 292, 'author_profile': 'https://Stackoverflow.com/users/292', 'pm_score': 0, 'selected': False, 'text': '<p>@Brian Leahy\nObviously if you are only operating on it as a Leg there is no need or reason to cast.  But if there is some DogLeg or Dog specific behavior, there are sometimes reasons that the cast is neccessary.</p>\n'}, {'answer_id': 46951, 'author': 'ben', 'author_id': 4607, 'author_profile': 'https://Stackoverflow.com/users/4607', 'pm_score': 2, 'selected': False, 'text': '<p>The concept that is causing you problems is described at <a href="http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)</a></p>\n'}, {'answer_id': 46959, 'author': 'shsteimer', 'author_id': 292, 'author_profile': 'https://Stackoverflow.com/users/292', 'pm_score': 0, 'selected': False, 'text': "<p>@Luke</p>\n\n<p>I think your perhaps misunderstanding inheritance.  Dog.GetLeg() will return a DogLeg object.  </p>\n\n<pre><code>public class Dog{\n    public Leg GetLeg(){\n         DogLeg dl = new DogLeg(super.GetLeg());\n         //set dogleg specific properties\n    }\n}\n\n\n    Animal a = getDog();\n    Leg l = a.GetLeg();\n    l.kick();\n</code></pre>\n\n<p>the actual method called will be Dog.GetLeg(); and DogLeg.Kick() (I'm assuming a method Leg.kick() exists)  there for, the declared return type being DogLeg is unneccessary, because that is what returned, even if the return type for Dog.GetLeg() is Leg.</p>\n"}, {'answer_id': 46962, 'author': 'Keith Sirmons', 'author_id': 1048, 'author_profile': 'https://Stackoverflow.com/users/1048', 'pm_score': 0, 'selected': False, 'text': '<p>You could also return the interface ILeg that both Leg and/or DogLeg implement.</p>\n'}, {'answer_id': 46964, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': '<pre><code>abstract class Animal\n{\n  public virtual Leg GetLeg ()\n}\n\nabstract class Leg { }\n\nclass Dog : Animal\n{\n  public override Leg GetLeg () { return new DogLeg(); }\n}\n\nclass DogLeg : Leg { void Hump(); }\n</code></pre>\n\n<p>Do it like this, then you can leverage the abstraction in your client:</p>\n\n<pre><code>Leg myleg = myDog.GetLeg();\n</code></pre>\n\n<p>Then if you need to, you can cast it:</p>\n\n<pre><code>if (myleg is DogLeg) { ((DogLeg)myLeg).Hump()); }\n</code></pre>\n\n<p>Totally contrived, but the point is so you can do this:</p>\n\n<pre><code>foreach (Animal a in animals)\n{\n   a.GetLeg().SomeMethodThatIsOnAllLegs();\n}\n</code></pre>\n\n<p>While still retaining the ability to have a special Hump method on Doglegs.</p>\n'}, {'answer_id': 46967, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 1, 'selected': False, 'text': "<p>Perhaps it's easier to see the problem with an example:</p>\n\n<pre><code>Animal dog = new Dog();\ndog.SetLeg(new CatLeg());\n</code></pre>\n\n<p>Now that should compile if you're Dog compiled, but we probably don't want such a mutant.</p>\n\n<p>A related issue is should Dog[] be an Animal[], or IList&lt;Dog> an IList&lt;Animal>?</p>\n"}, {'answer_id': 46968, 'author': 'Nir', 'author_id': 3509, 'author_profile': 'https://Stackoverflow.com/users/3509', 'pm_score': 0, 'selected': False, 'text': "<p>The important thing to remember is that you can use a derived type every place you use the base type (you can pass Dog to any method/property/field/variable that expects Animal)</p>\n\n<p>Let's take this function:</p>\n\n<pre><code>public void AddLeg(Animal a)\n{\n   a.Leg = new Leg();\n}\n</code></pre>\n\n<p>A perfectly valid function, now let's call the function like that:</p>\n\n<pre><code>AddLeg(new Dog());\n</code></pre>\n\n<p>If the property Dog.Leg isn't of type Leg the AddLeg function suddenly contains an error and cannot be compiled.</p>\n"}, {'answer_id': 46980, 'author': 'serg10', 'author_id': 1853, 'author_profile': 'https://Stackoverflow.com/users/1853', 'pm_score': 2, 'selected': False, 'text': "<p>Not that it is much use, but it is maybe interesting to note the Java does support covariant returns, and so this would work exactly how you hoped.  Except obviously that Java doesn't have properties ;)</p>\n"}, {'answer_id': 47010, 'author': 'vextasy', 'author_id': 3010, 'author_profile': 'https://Stackoverflow.com/users/3010', 'pm_score': 4, 'selected': False, 'text': "<p>Clearly, you'll need a cast if you're \noperating on a broken DogLeg.  </p>\n"}, {'answer_id': 47256, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 2, 'selected': False, 'text': '<p>You can use generics and interfaces to implement that in C#:</p>\n\n<pre><code>abstract class Leg { }\n\ninterface IAnimal { Leg GetLeg(); }\n\nabstract class Animal&lt;TLeg&gt; : IAnimal where TLeg : Leg\n { public abstract TLeg GetLeg();\n   Leg IAnimal.GetLeg() { return this.GetLeg(); }\n }\n\nclass Dog : Animal&lt;Dog.DogLeg&gt;\n { public class DogLeg : Leg { }\n   public override DogLeg GetLeg() { return new DogLeg();}\n } \n</code></pre>\n'}, {'answer_id': 47300, 'author': 'Ivan Hamilton', 'author_id': 4729, 'author_profile': 'https://Stackoverflow.com/users/4729', 'pm_score': 2, 'selected': False, 'text': '<p>It is a perfectly valid desire to have the signature an overriding method have a return type that is a subtype of the return type in the overridden method (<em>phew</em>). After all, they are run-time type compatible.</p>\n<p>But C# does not yet support &quot;covariant return types&quot; in overridden methods (unlike C++ [1998] &amp; Java [2004]).</p>\n<p>You\'ll need to work around and make do for the foreseeable future, as Eric Lippert stated in <a href="http://blogs.msdn.com/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx" rel="nofollow noreferrer">his blog</a>\n[June 19, 2008]:</p>\n<blockquote>\n<p>That kind of variance is called &quot;return type covariance&quot;.</p>\n<p>we have no plans to implement that kind of variance in C#.</p>\n</blockquote>\n'}, {'answer_id': 68313, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You can achieve what you want by using a generic with an appropriate constraint, like the following:</p>\n\n<pre><code>abstract class Animal&lt;LegType&gt; where LegType : Leg\n{\n    public abstract LegType GetLeg();\n}\n\nabstract class Leg { }\n\nclass Dog : Animal&lt;DogLeg&gt;\n{\n    public override DogLeg GetLeg()\n    {\n        return new DogLeg();\n    }\n}\n\nclass DogLeg : Leg { }\n</code></pre>\n'}, {'answer_id': 73720, 'author': 'munificent', 'author_id': 9457, 'author_profile': 'https://Stackoverflow.com/users/9457', 'pm_score': 1, 'selected': False, 'text': '<p>C# has explicit interface implementations to address just this issue:</p>\n\n<pre><code>abstract class Leg { }\nclass DogLeg : Leg { }\n\ninterface IAnimal\n{\n    Leg GetLeg();\n}\n\nclass Dog : IAnimal\n{\n    public override DogLeg GetLeg() { /* */ }\n\n    Leg IAnimal.GetLeg() { return GetLeg(); }\n}\n</code></pre>\n\n<p>If you have a Dog through a reference of type Dog, then calling GetLeg() will return a DogLeg. If you have the same object, but the reference is of type IAnimal, then it will return a Leg.</p>\n'}]
['https://Stackoverflow.com/questions/46933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/327/']