0

Is there a way for an interface to be automatically generic for the implementer class?

For example, I want to create an interface that will return a delegate off of the implementing class. (Actually I want it to return an array of multiple functions, but I'm simplifying here.)

The following should work:

public interface IParentFinder<ChildClass> 
{
    Func<ChildClass, int> GetParentIdFunction();
}

And then to implement it, I have to write this:

public class AClass : IParentFinder<AClass>
{
    int id;
    int parentId;

    static public Func<AClass, int> GetParentIdFunction()
    {
        return c => c.parentId;
    }
}

However I only ever want this interface to be used where the generic template matches the implementing class. Is there some convenience that I can use so that instead I can just write this:

public class AClass : IParentFinder
{
    ...
}

I was hoping there would be some baseType parameter I could use to specify the base type for generics. For example:

public interface IParentFinder
{
    Func <baseType, int> GetParentIdFunction();
}

edited for clarity

Erik Allen
  • 1,841
  • 2
  • 20
  • 36
  • i think you need to consider an abstract class, not an interface – Glenn Ferrie Feb 16 '15 at 20:37
  • So you will implement it like a non generic interface and expect it to work like generic? what if you have also a non generic interface with the same name? – Selman Genç Feb 16 '15 at 20:37
  • 1
    No, there isn't a way to do what you ask, not in that way at least. What is that you want to achieve? Why do you need to return a lambda expression instead of the parent id directly? – Sebastian Piu Feb 16 '15 at 20:37
  • I would have preferred to have a static interface but those aren't possible in C#. This is to workaround that. I want to find out a list of relationships a class has, so I can compare it to a list of relationships that I am looking for with a specific id. – Erik Allen Feb 16 '15 at 20:43

2 Answers2

0

No, there is no feature in C# that does this.

Servy
  • 202,030
  • 26
  • 332
  • 449
0

As any other parameter, either method or generic parameters, a generic interface type parameter requires an argument. A parameter without an argument isn't a parameter at all.

Maybe C# vNext could implement something like default generic parameter value:

public class A<T> where T : default(string) { ... }

...or who knows what. But, for now, a generic parameter requires an argument. And, after all, this wouldn't fit what you're looking for in your case - auto-magically-infered generic parameters... -.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206