Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define/constrain a member as implementing two interfaces, without generics?

The following code shows what I would like to do; that is, I would like to constrain anObject, so that it can be used as a parameter to various methods with use IInterfaceOne or IInterfaceTwo, where neither inherits from the other.

public interface IInterfaceOne { }
public interface IInterfaceTwo { }

public class Implementation : IInterfaceOne, IInterfaceTwo
{
}

public interface IInterfaceOneAndTwo : IInterfaceOne, IInterfaceTwo { }

public class UsingImplementation
{
    IInterfaceOneAndTwo anObject = (IInterfaceOneAndTwo)(new Implementation()); //fails because Implementation doesnt acctually implement IInterfaceOneAndTwo
}

This example fails however as IInterfaceOneAndTwo is an interface in its own right, and Implementation does not implement it.

I know if I used generics I could constrain them, but I am wondering, if there is a way to do this without generics?

Is there a way to say anObject shall implement IInterfaceOne and IInterfaceTwo, without using IInterfaceOneAndTwo?

like image 245
sebf Avatar asked Dec 22 '22 02:12

sebf


1 Answers

Not the way you have it currently. Only generic constraints have that ability.

You could rewrite it to use generics:

public class UsingImplementation<T>
   where T : IInterface1, IInterface2, new()
{
    T anObject = new T();

    void SomeMethod() {
       anObject.MethodFromInterface1();
    }
}
like image 184
Daniel A. White Avatar answered Dec 24 '22 00:12

Daniel A. White