Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# overload 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?

like image 815
Yippie-Ki-Yay Avatar asked Dec 07 '25 10:12

Yippie-Ki-Yay


2 Answers

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.

like image 167
Jon Skeet Avatar answered Dec 10 '25 00:12

Jon Skeet


Yes. That is how the compiler works.

like image 26
Daniel A. White Avatar answered Dec 10 '25 01:12

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!