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.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
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.
Note: You also can use interface names as return types. In this case, the object returned must implement the specified 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.
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);
}
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With