Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How can I have an type that references any object which implements a set of Interfaces?

How can I have a type reference that refers to any object that implements a set of interfaces?

For example, I can have a generic type like this:

Java:

public class Foo<T extends A & B> { }

C#

public class Foo<T> where T : A, B { }

That's how to have a class-wide generic type. However, I'd like to simply have a data member which references any object that extends a given set of interfaces.

Example:

public class Foo
{
    protected <? extends A, B> object;

    public void setObject(<? extends A, B> object)
    {
        this.object = object;
    }
}

If it's possible to have this sort of type syntax, how could I do it in both Java and C#?


I realize I can just create another interface that extends all desired interfaces. However, I don't see this as optimal, as it needlessly adds another type whose sole purpose is to get around syntax. Granted this is a very minor issue, but in terms of elegance it's a bit galling.

like image 745
CodeBunny Avatar asked Nov 13 '11 22:11

CodeBunny


2 Answers

My Java has become a bit rusty through 2years of inactivity.

Here's my C# approach: (see https://ideone.com/N20xU for full working sample)

public class Foo
{
    private IInterface1 _object; // just pick one

    public void setObject<T>(T obj)
        where T : IInterface1, IComparable<T>, IEtcetera
    {
        // you now *know* that object supports all the interfaces
        // you don't need the compiler to remind you
        _object = obj; 
    }

    public void ExerciseObject()
    { 
        // completely safe due to the constraints on setObject<T>
        IEtcetera itf = (IEtcetera) _object;

        // ....
    }
like image 65
sehe Avatar answered Nov 12 '22 20:11

sehe


As far as I know, You cannot create a variable with constraints on it, you can only create a variable of a given type. The type has the constraints. This means you have to define a type that has the constraints you desire, then create the variable with that type.

This seems logical to me, and I don't see why you find it "galling" to have to define a type for what you need.

like image 39
Erik Funkenbusch Avatar answered Nov 12 '22 22:11

Erik Funkenbusch