Reputation: 3563
Why after starting the program will be displayed C::Foo(object o)
?
using System;
namespace Program
{
class A
{
static void Main(string[] args)
{
var a = new C();
int x = 123;
a.Foo(x);
}
}
class B
{
public virtual void Foo(int x)
{
Console.WriteLine("B::Foo");
}
}
class C : B
{
public override void Foo(int x)
{
Console.WriteLine("C::Foo(int x)");
}
public void Foo(object o)
{
Console.WriteLine("C::Foo(object o)");
}
}
}
I can not understand why when you call C :: Foo
, selects method with the object
, not with int
. What's the class B
and that method is marked as override?
In class C
, there are two methods with the same name but different parameters, is it not overloaded? Why not? Does it matter that one of the methods to be overridden in the parent? It somehow disables overload?
Upvotes: 14
Views: 533
Reputation:
Declarations that include an override modifier are excluded from the set.
Overloading base method in derived class
Derived class using the wrong method
Instead use override
you should use new
:
public new void Foo(int x)
{
Console.WriteLine("C::Foo(int x)");
}
public void Foo(object o)
{
Console.WriteLine("C::Foo(object o)");
}
Upvotes: 4
Reputation: 166606
Have a look at Member lookup
First, the set of all accessible (Section 3.5) members named N declared in T and the base types (Section 7.3.1) of T is constructed. Declarations that include an override modifier are excluded from the set. If no members named N exist and are accessible, then the lookup produces no match, and the following steps are not evaluated.
So according to this, it would use
public void Foo(object o)
first
Upvotes: 9