Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force an implementing class to return an object of its own type?

Tags:

c#

interface

I want to make an interface in C# that defines a method that always returns an object of the implementing class, thus:

public interface IParser {
    IParser Parse(string s);
}

public class Parser : IParser {
    public Parser Parse(string s) {
        return new Parser(s);
    }
}

Can I force an implementing class to return an object of its own type? If possible, then how? Or is generics the answer here?

NB: The code is just an illustration, not something that's supposed to run.

like image 654
Cros Avatar asked Nov 06 '09 15:11

Cros


People also ask

Can a class return its own object?

Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.

What is explicit implementation?

Explicit implementation is also used to resolve cases where two interfaces each declare different members of the same name such as a property and a method. To implement both interfaces, a class has to use explicit implementation either for the property P , or the method P , or both, to avoid a compiler error.

CAN interface have return type in Java?

Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.

How can we avoid implementing all methods interface?

Declare the missing methods abstract in your class. This forces you to declare your class abstract and, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects.


2 Answers

Generics is the answer here.

public interface IParser<T> where T:IParser<T> {
    T Parse(string s);
}

public class Parser : IParser<Parser> {
    public Parser Parse(string s) {
        return new Parser(s);
    }
}
like image 195
BennyM Avatar answered Oct 14 '22 11:10

BennyM


Not in the interface declaration, no. The best you could manage is with generics:

public interface IParser<T>
    where T: IParser<T>
{
    T Parse(string s);
}

public class Parser
 : IParser<Parser>
{
    public Parser Parse(string s)
    {
       return new Parser(s);
    }
}

This doesn't force the implementation to return it's own type, but at least it allows it to do so. This is why the IClonable interface returns an object from its Clone method, rather than a specific type.

----Edit----

Something to remember on this question: let's say that my code, for which you don't have any knowledge of the implementation, returns an IParser, and your code calls the Parse method. What object do you expect to be returned, not knowing the concrete type of returned IParser reference? I think you're trying to use interfaces for something they're not meant to do...

like image 26
FacticiusVir Avatar answered Oct 14 '22 12:10

FacticiusVir