Home > Enterprise >  Interface with different parameter type
Interface with different parameter type

Time:07-04

I want to implement an interface in C# and there is a function called Testfunction.

For example:

public interface Test
{
    void Testfunction(type filter);
}

But I want to make all the classes inherit this interface can implement this Testfunction with all different type of parameters, is it possible?

CodePudding user response:

You can try using generics, e.g.:

public interface ITest<T>
{
    void TestFunction(T filter);
}

then you can put:

// Here filter is of type int
public class MyTestInt : ITest<int> {
  public void TestFunction(int filter) {
    ...
  }
}

// And here filter is of type string
public class MyTestString : ITest<string> {
  public void TestFunction(string filter) {
    ...
  }
}

etc.

CodePudding user response:

Yes, with Generics.

public interface Test<T>
{
    void TestFunction(T filter);
}

Implementers would then do

public class Foo : Test<Bar>
{
    public void TestFunction(Bar filter)
    {
        // ...
    }
   
}

You can even add constraints to your generic parameter (T), as documented here, for example you could restrict it so that any type used as a type parameter must implement another specific interface, and a bunch more stuff

You could also make only the method generic, like so

public interface Test
{
    void TestFunction<T>(T filter);
}

public class Foo : Test
{
    public void TestFunction<Bar>(Bar filter)
    {
        // ...
    }
}

This has the advantage that you could define a bunch of methods, each with maybe varying type parameters and not have a bunch of type parameters for your interface. Although, it is normally preferred to make the interface itself generic, so you save yourself (and any future dev) some duplicate typing.

But there's also a major disadvantage, image you have 2 methods, TestFunction1<T1> and TestFunction2<T2>, then there's no guarantee that T1 from TestFunction1 is the same type as T2 from TestFunction2, where as if you specify the type parameter on the entire interface you know that it will always be the same type in all methods

I've put together a "little" demo of both ways in action here

  • Related