Question

Is it possible to somehow implement the following scheme:

public interface ISomething
{
    void Go(ISpecific specific);

    void Go(Object o);
}

so that on every Go(ISpecific) call the first overload would be called and for the calls with any other possible objects the class would fallback to the Go(Object) implementation?

Was it helpful?

Solution

That's how it will work by default - but using the compile-time types. If you have Go(foo) and the compile-time type of foo doesn't implement ISpecific, it will call the second method even if the object that foo refers to at execution time implements ISpecific. If you want this decision to be made dynamically at execution time, and if you're using C# 4, you could write:

dynamic value = GetValue();
something.Go(value);

... and at execution time, the correct overload will be selected.

OTHER TIPS

Yes. That is how the compiler works.

Yes it is possible to do that. Note though that the decision on which overload to take will be done based on the compile time type of the reference.

ISpecific specificVar = null;
something.Go(specificVar);  // ISomething::Go(ISpecific)
object obj = specificVar;
something.Go(obj);  // ISomething::Go(object)

Yes it definitely works, any object that is not ISpecific will call the object overload.

I wrote a console app to check.

it outputs

Object 
Object
Specific

class Program
{
    static void Main()
    {
        Object aSpecific = new Object();
        String nonSpecific = "nonSpecific";
        ISpecific specific = new Specific();

        ISomething something = new Something();

        something.Go(aSpecific);
        something.Go(nonSpecific);
        something.Go(specific);

        Console.ReadKey();
    }
}

interface ISpecific
{
    void GoGo();
}

interface ISomething
{
    void Go(ISpecific specific)
    void Go(Object o)
}

Class Specific : ISpecific
{
    public Specific() { }

    public void GoGo()
    {
         Console.WriteLine("Specific");
    }
}

Class Something : ISomething
{
    public Something() { }

    public void Go(ISpecific specific)
    {
        specific.GoGo()
    }

    public void Go(Object o)
    {
        Console.WriteLine("Object");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top