박상욱
박상욱

Reputation: 19

Interface with different parameter type

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?

Upvotes: 1

Views: 1266

Answers (2)

MindSwipe
MindSwipe

Reputation: 7855

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

Upvotes: 5

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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.

Upvotes: 6

Related Questions