Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need an explicit interface declaration here? (C#) [duplicate]

The use case is some what like this:

public class SomeClass : ICloneable
{
    // Some Code

    // Implementing interface method
    public object Clone()
    {
        // Some Clonning Code
    }
}

Now my question is Why is it not possible to use "SomeClass(As it is derived from object)" as a return type of Clone() method if we consider the Funda's of Covariance and Contravariance?

Can somebody explain me the reason behind this implementation of Microsoft ????

like image 628
Amit Avatar asked Nov 21 '22 03:11

Amit


1 Answers

Let me rephrase the question:

Languages such as C++ allow an overriding method to have a more specific return type than the overridden method. For example, if we have types

abstract class Enclosure {}
class Aquarium : Enclosure {}
abstract class Animal 
{
    public virtual Enclosure GetEnclosure();
}

then this is not legal in C# but the equivalent code would be legal in C++:

class Fish : Animal
{
    public override Aquarium GetEnclosure() { ... 

What is this feature of C++ called?

The feature is called "return type covariance". (As another answer points out, it would also be possible to support "formal parameter type contravariance", though C++ does not.)

Why is it not supported in C#?

As I've pointed out many times, we don't have to provide a reason why a feature is not supported; the default state of all features is "not supported". It's only when huge amounts of time and effort are put into making an implementation that a feature becomes supported. Rather, features that are implemented must have reasons for them, and darn good reasons at that considering how much it costs to make them.

That said, there are two big "points against" this feature that are the primary things preventing it from getting done.

  1. The CLR does not support it. In order to make this work we'd basically have to implement the exactly matching method and then make a helper method that calls it. It's doable but it gets to be messy.

  2. Anders thinks it is not a very good language feature. Anders is the Chief Architect and if he thinks it is a bad feature, odds are good its not going to get done. (Now, mind you, we thought that named and optional parameters was not worth the cost either, but that did eventually get done. Sometimes it becomes clear that you do have to grit your teeth and implement a feature that you don't really like the aesthetics of in order to satisfy a real-world demand.)

In short, there are certainly times when it would be useful, and this is a frequently requested feature. However, it's unlikely that we're going to do it. The benefit of the feature does not pay for its costs; it considerably complicates the semantic analysis of methods, and we have no really easy way to implement it.

like image 108
Eric Lippert Avatar answered Dec 16 '22 00:12

Eric Lippert