I was browsing through Github when I noticed an interface in C# that had the following:
public interface IAction : IPrototype<IAction>
I have never seen this before. So I was curious what this exactly means or what it does and if this is applicable to things other than interfaces?
Is this a C# specific syntax for a specific behavior? (Is it useful in other OOP languages)
Sorry, if this is a really noob question but, I don't even know what this is called so I couldn't figure out exactly how to simply google it :P
That means that IAction inherits a generic IPrototype<T> interface where the type is IAction. IPrototype<T> may define a member to consume or produce a T, in this case it would be a IAction.
It's an interface that inherits from a generic interface.
To me this looks like an interface that enforces the prototype pattern by implementing the curiously recursive template pattern. More info can be found here https://zpbappi.com/curiously-recurring-template-pattern-in-csharp/.
Essentially, you are able to define an interface that contains methods that return or consume strongly typed instances of the implementor. Without the pattern the best you could do is return an instance of the base interface.
The prototype pattern is a pattern that allows for a class to be cloned, so I guess that the IPrototype interface has a method called Clone that returns T. In this case it would return IAction.
public interface IPrototype<T> where T : IPrototype<T>
{
// enforces a clone method returning the sub class
T Clone();
}
Related
To illustrate my question I've written a simple method:
public static T ConvertTo<T>(...)
where T : ISomeInterface
{
// return an instance of T
}
Obviously this method can be called like
ConvertTo<ISomeInterface>(...)
But in my case it doesn't make sense. Method should return an instance of a class that implements ISomeInterface. At now I throw NotSupportedException for any type the method unable to work with and I satisfied with this solution. But if I could filter out an interface itself in compile time it would be better.
So my question is: Is it possible to constrain generic parameter with implementations of an interface?
So my question is: Is it possible to constrain generic parameter with implementations of an interface?
No, there is not. You have found the best-fitting solutions: class and new(), where class only filters out structs, etc. class and new() used together is the only real solution, but a solution that is actually too strict.
You might have some luck with code analyzers or AOP where can filter out bad calls on compile-time.
I'm searching for a pattern to aggregate interface methods into one generic method.
Better to make an example of what I'm trying to do
Consider that I have an interface with more then 40 methods which have all different responsibilities but the implementations of these methods are equal besides of function name an parameters.
interface MultiMethod{
public TypeA A (p1,p2);
public TypeA B (p1);
public TypeC C (p5,p3,p2);
.
.
.
}
Implementation Class
class MultiMethodeService : MultiMethod
In the MultiMethodeService I need to Implement all Interface methods, but the implementation of the methods is not real different.
Like:
public TypeA A (p1,p2){
proxy.call("remoteA").params(p1,p2);
}
public TypeB B (p1){
proxy.call("remoteB").params(p1);
}
I want to replace the implementation of the methods with one generic method that uses reflection.
The generic method derives
the parameters form the MultiMethod interface
the method name from the MultiMethode interface to invoke the equal proxy call
For me it is clear how implement the generic method, but how is it possible, when I have a generic method to also have the equal semantic like without a generic implementation.Deeper meaning code complition (intellisense) should work for the generic implementation equal to the OOP implementation.
When I afterwords want to use the service object of MultiMethodService like :
var service = new MultiMethodService()
service.A(p1,p2)
Some naive idea was to implement an enum{"A","B"}
service.callGeneric(enum.A, p1,p2);
service.callGeneric(enum.B, p1);
which is not really nice.
Again why would you implement this an not the straight forward OOP solution?
Prevent implementing the same method again and again with only a few changes that could be deduced by reflection from an interface
DRY, Don't reaped yourself. If the interface changes or parameter types, only refactor these but not the whole remote calls (interface implementation)
If you could provide any pattern or idea, your help is highly appreciated.
offtopic
More explanation needed? Lets say I have this javascript (typescript) interface in c# which represents the typescript service to c#. Additionally I have the c# classes reflecting the javascript classes. Now I have an mechanism to call from C# into javascript to compute the result. see here. Which is implemented in the interface methods. This repeats 46 times, and if something changes I have to refactor some of the implementation. How can I prevent reimplementing the inteface methods by using something generic. With the possibility to use afterwords the service like service.getSyntacticDiagnostics(...), I can rephrase this with, code completion(intellisense) should work equally to OOP style code.
I use interfaces for decoupling my code. I am curious, is the usage of explicit interface implementation meant for hiding functionality?
Example:
public class MyClass : IInterface
{
void IInterface.NoneWillCall(int ragh) { }
}
What is the benefit and specific use case of making this available only explicitly via the interface?
There are two main uses for it in my experience:
It allows you to overload methods by return value. For example, IEnumerable<T> and IEnumerable both declare GetEnumerator() methods, but with different return types - so to implement both, you have to implement at least one of them explicitly. Of course in this question both methods are provided by interfaces, but sometimes you just want to give a "normal" method with a different type (usually a more specific one) to the one from the interface method.
It allows you to implement part of an interface in a "discouraging" way - for example, ReadOnlyCollection<T> implements IList<T>, but "discourages" the mutating calls using explicit interface implementation. This will discourage callers who know about an object by its concrete type from calling inappropriate methods. This smells somewhat of interfaces being too broad, or inappropriately implemented - why would you implement an interface if you couldn't fulfil all its contracts? - but in a pragmatic sense, it can be useful.
One example is ICloneable. By implementing it explicitly, you can have still have a strongly typed version:
public class MyClass : ICloneable {
object ICloneable.Clone() {
return this.Clone();
}
public MyClass Clone() {
return new MyClass() { ... };
}
}
It is not meant for hiding methods but to make it possible to implement two methods with the same signature/name from different interface in to different ways.
If both IA and IB have the operation F you can only implement a different method for each F by explicitly implementing the interfaces.
It can be used for hiding. For example, some classess that implement IDisposable do so explicitly because they also have a Close() method which does the same thing.
You can also use the explicit interface definitions for when you are implementing two interfaces on one class and there is a signature clash and the functionality differs depending on the interface. However, if that happens it is usually a sign that your class is doing too much and you should look at splitting the functionality out a bit.
I would like to pass a generic interface to a function:
private I<T> CreateStubRepository<T, I >()
where I : aGenericBaseClass
So i was wondering if generic interfaces implement a base class or specific interface?
I know by using reflection you can test if it is a generic class but I dont see that helping me
Well. What's the point of forcing the usage of any interface? I really do not get it (or your question).
You should more likely do something like this:
public interface IMyRepository<T>
{
}
public class Repository<T> : IMyRepository<T>
{
}
private IMyRepository<TEntity> CreateStubRepository<TEntity>()
{
return new Repository<TEntity>();
}
var repos = CreateStubRepository<User>();
Update
thanks for your answer but thats not what I am asking. What I want to know is does a class that implements a generic interface have a base class or does it inherit from an interface? I dont want to force any interface its more a question of is the object passed generic
Classes do not inherit interfaces. They implement them. The different is subtle but important.
A class can only inherit another class. This means that if you do not specify that a class inherits from another it will still inherit from object. And that wont change no matter how many interfaces a class implement.
class MyClass : ICoolInterface // inherits object
class MyList : ArrayList, ISomeInterface // inherits ArrayList
class MyGenericList<T> : IList<T> // inherits object.
Generic or non-generic classes can implement or inherit from generic or non-generic interfaces and classes. The only limitation is that the full type of any interface/class implemented/inherited from must be discernible given the full type of the class doing the implementing or inheriting. For example, a Foo<Bar> might inherit from FooBase and implement IDisposable; a FnordDuffleBag might inherit from DuffleBag<Fnord> and implement IReachInto<Fnord>.
Thanks for all the comments I think i was going in the wrong direction, What I was hoping for was that when I applied to a class the framework would know that it inherited from a base class or interface of say aGenericItemBaseClass before it constructed the class at runtime.
Yes I know that I can create a generic class with type parameters and use that but thats not what I was asking (although you may have got that impression from my posting).
At runtime I know that when using reflection I can determine if a class is generic by calling : IsGenericType which returns true if a type is generic.
So what I wanted to know which may have been explained poorly is, when using template types is there anyway to determine if that type is a generic type? It appears the answer is No the IL interperates the class as generic not the compiler.
I have seen this statement in many of the documention samples, like here
This class is the default implementation of the "ISomeInterface" interface
what exactly this means ? Thanks
This is somewhat misleading, since an interface, by definition, provides no implementation.
However, many portions of the framework try to make life easier - so they provide a method which takes an interface, but also provides an overload with no parameters. A good example is List<T>.Sort.
The documentation here is suggesting that, if you use a method that would normally require an IComparer<T>, but use it via some overload that doesn't, you'll get the referenced "default implementation" used instead.
However, this is really an "implementation detail" of classes unrelated to the interface itself. I personally think this is a poor choice of words in the documentation, and should be something more like:
Many types in the framework rely on a common implementation of this interface provided by
the Comparer class.
This would, in my opinion, provide a more clear meaning to this...
It means that when you call the Sort method without argument (without explicitly specifying a comparer) it will use this default implementation.
This means this class is the one implementing the interface. It points to the object that implements the interface itself without any derived or inherited members, but plainly the interface. This is the class that cirectly corresponds to this interface.
public interface IComparer {
// Some members to implement here.
}
public class Comparer : IComparer {
// IComparer members implementation
}