Mark
Mark

Reputation: 71

How to call generic overloaded method in C#

Not very familiar with C# and generics so I may be missing something obvious, but:

Given:

public interface IA { }

public interface IB
{  void DoIt( IA x );
}

public class Foo<T> : IB where T : IA
{
    public void DoIt( IA x )
    {  DoIt(x); // Want to call DoIt( T y ) here
    }

    void DoIt( T y )
    {  // Implementation
    }
}

1) Why doesn't the method void DoIt(T y) satisfy the DoIt method implementation required by interface IB?

2) How can I call DoIt(T y) from within DoIt( IA x )?

Upvotes: 2

Views: 89

Answers (1)

Dennis
Dennis

Reputation: 37770

1) Because any T is IA (this is given from contraint), but not every IA is T:

class A : IA {}
class B : IA {}

var foo_b = new Foo<B>();
var a = new A();

// from the point of IB.DoIt(IA), this is legal;
// from the point of Foo<B>.DoIt(B y), passed argument is not B
foo_b.DoIt(a);

2) If you are sure, that x is T, then use cast:

public void DoIt( IA x )
{  
    DoIt((T)x);
}

if x can be anything, and DoIt(T) can be optional, use as:

public void DoIt( IA x )
{  
    DoIt(x as T);
}

void DoIt( T y )
{
    if (y == null)
        return;

    // do it
}

Otherwise you can throw exception or consider another approach, depending on particular use case.

Upvotes: 3

Related Questions