I was just reading this answer
Which overload is called and how?
by Jon Skeet and I just done understand how overload resolution gets done at compile time – How is that possible?? You dont know the type of the object till you run??
I always thought that all method calls were done at run time (late binding)
What are the exceptions to that??
I ll give an example:
public void DoWork(IFoo)
public void DoWork(Bar)
IFoo a = new Bar();
DoWork(a)
Which method gets called here and why?
When a method call is encountered by the compiler the types of all the parameters are known because C# is a statically-typed language: all expressions and variables are of a particular type and that type is definite and known at compile time.
This is ignoring
dynamicwhich slightly complicates things.Edit: This is a response to your edit. For clarity, I translated your code into the following:
You are asking which method is called here (
Test.DoWork(IFoo)orTest.DoWork(Bar)) when invoked ast.DoWork(a)inMain. The answer is thatTest.DoWork(IFoo)is called. This is basically because the the parameter is typed as anIFoo. Let’s go the specification (§7.4.3.1):The issue here (see the bolded statement) is that there is no implicit conversion from
IFootoBar. Therefore, the methodTest.DoWork(Bar)is not an applicable function member. ClearlyTest.DoWork(IFoo)is an applicable function member and, as the only choice, will be chosen by the compiler as the method to invoke.