Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why overloading does not work?

Tags:

c#

overloading

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?

like image 640
Dima Kozyr Avatar asked Feb 12 '14 04:02

Dima Kozyr


People also ask

Why method overloading is not possible?

In java, method overloading is not possible by changing the return type of the method only because of ambiguity.

Why overloading is not possible in C?

Function overloading is a feature of Object Oriented programming languages like Java and C++. As we know, C is not an Object Oriented programming language. Therefore, C does not support function overloading.

Why overloading is not possible in python?

Why no Function Overloading in Python? Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.

Why main method is not overloading in Java?

No, we cannot override main method of java because a static method cannot be overridden. The static method in java is associated with class whereas the non-static method is associated with an object. Static belongs to the class area, static methods don't need an object to be called.


1 Answers

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

like image 156
Adriaan Stander Avatar answered Sep 30 '22 16:09

Adriaan Stander