Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generic interface multiple times on the same class

I have an interface

interface IInterface<E>{
    E Foo();
}

I then create a class like this

class Bar : IInterface<String>, IInterface<Int32> {
}

This actually works out quite well, except I need to define one of the two functions with the interface explicit, like this:

class Bar : IInterface<String>, IInterface<Int32> {
    String Foo();
    Int32 IInterface<Int32>.Foo();
}

The drawback is that I have to do a cast every time I want to reach the Foo() which has the explicit interface.

What are the best practices when dealing with this?

I'm doing a very performance dependent application, so I really don't want to do a million casts per second. Is this something the JIT will figure out, or should I store a casted version of the instance in itself?

I have not tried this specific code, but it looks awfully close to what I am doing.

like image 202
Marcus Johansson Avatar asked Jul 11 '12 10:07

Marcus Johansson


1 Answers

You cannot override by return type, but if you want to avoid casting you could turn your return type into an out parameter:

interface IInterface<E> {
    void Foo(out E result);
}

class Bar : IInterface<string>, IInterface<int> {
    public void Foo(out string result) {
        result = "x";
    }
    public void Foo(out int result) {
        result = 0;
    }
}

static void Main(string[] args) {
    Bar b = new Bar();
    int i;
    b.Foo(out i);
    string s;
    b.Foo(out s);
}
like image 199
Paolo Tedesco Avatar answered Oct 15 '22 12:10

Paolo Tedesco