14

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?

therealrootuser
  • 10,215
  • 7
  • 31
  • 46
Amazing User
  • 3,473
  • 10
  • 36
  • 75
  • Simple answer. Don't do this. Don't include an overload with object. Use generics or even dynamic not object – Mick Feb 12 '14 at 05:51

2 Answers2

9

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

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
4

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)");
}
Community
  • 1
  • 1