Nicolas
Nicolas

Reputation: 960

Returning the derived class instead of an interface

Is it possible to return the derived class in an interface definition in C#? Some kind of return type covariance.

For example:

public interface IAnimal
{
    this GetAnimal();
}

public class Dog : IAnimal
{
    Dog GetAnimal() { return new Dog(); }
}

Upvotes: 0

Views: 88

Answers (3)

Gediminas Masaitis
Gediminas Masaitis

Reputation: 3212

C# doesn't support return type covariance, at least as of C# 6. It is a very commonly requested feature on the Roslyn GitHub, and was long before Roslyn even existed.

Eric Lippert wrote in his answer:

The feature is not implemented because no one here ever implemented it. A necessary but insufficient requirement is that the feature's benefits exceed its costs.

The costs are considerable. The feature is not supported natively by the runtime, it works directly against our goal to make C# versionable because it introduces yet another form of the brittle base class problem.

So sit back, hold tight, and cross your fingers for C# 7/8/9. But don't get your hopes up too much - as said, it's a high-cost low-benefit feature that would likely require modifications to the CLR.

For now, take a look at Christos' answer.

Upvotes: 1

Spark
Spark

Reputation: 11

Sure if you pass the derived class as a type constraint :)

public interface IAnimal<T>
{
    T GetAnimal();
}

public class Dog : IAnimal<Dog>
{
    public Dog GetAnimal() { return new Dog(); }
}

Upvotes: 1

Christos
Christos

Reputation: 53958

Is it possible to return the derived class in an interface definition in C#?

Yes it is, if you define a generic interface.

public interface IAnimal<T>
{
    T GetAnimal();
}

public class Dog : IAnimal<Dog>
{
    public Dog GetAnimal() { return new Dog(); }
}

You could read further on this here.

Upvotes: 2

Related Questions