Ivan
Ivan

Reputation: 64227

How to sum interfaces in a variable definition in C#?

Say we have got 2 interfaces: IOne and ITwo and I want to define a function that accepts arguments of any type that implements both of these interfaces at the same time. How?

Upvotes: 1

Views: 219

Answers (2)

user1968030
user1968030

Reputation:

You can add an interface that both ITwo and IOne inherit from it.

public void SomeFunction(INumber argument)
{         
} 
public interface INumber
{
} 
public interface ITwo : INumber
{
}
public interface IOne : INumber
{
}

or use Generic:

public void SomeFunction<T>(T argument) where T : IOne, ITwo
{   
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

You can do it like this:

interface IOne {void Hello();}
interface ITwo {void World();}

static void Foo<T>(T arg) where T : IOne, ITwo {
    arg.Hello();
    arg.World();
}

Upvotes: 4

Related Questions