Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C# doesn't allow inheritance of return type when implementing an Interface

Tags:

Is there any rational reason why the code below is not legal in C#?

class X: IA, IB {     public X test() // Compliation Error, saying that X is not IB     {         return this;     } }  interface IA  {     IB test(); } interface IB { }; 
like image 523
Piotr Czapla Avatar asked Aug 23 '09 21:08

Piotr Czapla


People also ask

Why C is the best language?

The programs that you write in C compile and execute much faster than those written in other languages. This is because it does not have garbage collection and other such additional processing overheads. Hence, the language is faster as compared to most other programming languages.

Why is C used?

C is a general-purpose programming language and can efficiently work on enterprise applications, games, graphics, and applications requiring calculations, etc. C language has a rich library which provides a number of built-in functions. It also offers dynamic memory allocation.

Why should you learn C?

C is very fast in terms of execution time. Programs written and compiled in C execute much faster than compared to any other programming language. C programming language is very fast in terms of execution as it does not have any additional processing overheads such as garbage collection or preventing memory leaks etc.

Why is C language named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C". C is about the tone C.


1 Answers

UPDATE: This answer was written in 2009. After two decades of people proposing return type covariance for C#, it looks like it will finally be implemented; I am rather surprised. See the bottom of https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/ for the announcement; I'm sure details will follow.


This feature is called "return type covariance". C# does not support it for the following reasons:

1) The CLR doesn't support it. To make it work in C#, we'd have to just spit a whole bunch of little helper methods that do casts on the return type to the right thing. There's nothing stopping you from doing that yourself.

2) Anders believes that return type covariance is not a good language feature.

3) \We have lots of higher priorities for the language. We have only limited budgets and so we try to only do the best features we can in any given release. Sure, this would be nice, but it's easy enough to do on your own if you want to. Better that we spend the time adding features that improve the developer experience or add more representational power to the language.

like image 70
Eric Lippert Avatar answered Oct 21 '22 10:10

Eric Lippert