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.
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);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With