Not sure if this is C# 4+ specific, but just noticed this.
Consider the following classes:
class Base
{
protected void Foo(object bar, DayOfWeek day)
{
}
}
class Program : Base
{
protected void Foo(object bar, object baz)
{
}
void Bar(DayOfWeek day)
{
Foo(new { day }, day);
}
}
The call to Foo in Bar, resolves to Foo(object, object).
While changing it to:
class Base
{
}
class Program : Base
{
protected void Foo(object bar, object baz)
{
}
protected void Foo(object bar, DayOfWeek day)
{
}
void Bar(DayOfWeek day)
{
Foo(new { day }, day);
}
}
The call to Foo in Bar, resolves to Foo(object, DayOfWeek).
My understanding is that it should always resolve as in the second example.
Is this a ‘bug’ or just my lack of understanding (or ignorance)?
Update:
Thanks for the answers. As I have found out, one can use base. to call the method in the base class. The problem comes back however when adding another derived class in the mix.
class Base
{
protected void Foo(object bar, DayOfWeek day)
{
}
}
class Program : Base
{
protected void Foo(object bar, object baz)
{
}
void Bar(DayOfWeek day)
{
base.Foo(new { day }, day);
}
}
class Derived : Program
{
void Baz(DayOfWeek day)
{
base.Foo(new { day }, day);
}
}
The base. call works in Program, but then resolves to Foo(object, object) in Derived.
How would one call Foo(object,DayOfWeek) from Derived then without having to create ‘redundant’ methods in Program ?
I think for resolving method call it looks in its class first, since
DayOfWeekcan be passed asobjecttype, it calls class own method, not the one from the base class.In the second case, the method call resolves to a the more particular type parameter, therefore
Foo(object bar, DayOfWeek day)gets called.From MSDN – Method resolution.