The general rule is that I want to say, ‘T has a method with a String parameter which will return List.’ Put verbosely, we might call the interface ICanCreateListOfObjectsFromString. A possible application might be search.
It feels like it’d be nice to have a static method in my interface, but I know that’s not allowed in C#. What is another approach to specify this kind of contract implementation on a class?
Edit: I would like to have the following code:
public interface ISearch { static List<T> Search<T>(String s); } public class MyObject : ISearch { List<MyObject> Search(string s) { //... } } public List<T> DoFooSearch<T:ISearch> () { return T.Search('Foo'); } public List<T> DoBarSearch<T:ISearch> () { return T.Search('Bar'); }
You can probably see why this code won’t compile, but it expresses the spirit of what I’d like to achieve. I hope this clarifies my intention a bit.
Sounds like you’re trying to implement a Mixin… Something of that sort exists in C# 3.0, and they are named ‘Extension Methods’.
What do allow you to do? Well, they allow you to create functions that work in types that you specify, and ‘add’ methods to them. Since that type can be an interface, this lets you define concrete functions for an interface.
Admittedly, these functions aren’t part of the interface code itself, but they also aren’t part of any of the implementation of the interface. So it’s a ‘glass half full’ scenario.
(A brief search led me to Implementing Mixins with C# Extension Methods.)
Alternatively: if you don’t require multiple inheritance for the classes that implement your interface, you can use abstract classes instead of interfaces, and implement concrete functions directly in them. But then again, that means you give up on inheriting from anything but that class (and implementing other interfaces.)