-6

As written in topic - in C# what is the difference between method overloading and polymorphism?

If you know then it would be better if you could give an answer with some examples.

lee-m
  • 2,269
  • 17
  • 29
Sameer
  • 19
  • 3
  • 1
    method overloading is still part of the polymorphism. the object behaves differently when a given method is called according to which arguments are passed. The deeper form of polymorphism is given by inheritance and interface implementation – Diego D Aug 01 '23 at 08:59
  • With method overloading, the function is chosen at compile time, depending on the number and type of arguments passed to the function. With polymorphism, the function to execute is chosen at runtime, depending on the actual type of the object. – Peter Bruins Aug 01 '23 at 09:00
  • Though it must also have been a duplicate in 2014, six years after the launch of Stack Overflow. – Peter Mortensen Aug 11 '23 at 00:39

1 Answers1

3

Both method overloading and overriding (in the context of inheritance) are forms of polymorphism. To be more precise:

  • Method overloading is a form of compile-time polymorphism, where methods in the same class share the same name but have different parameters. The compiler determines the correct method to call based on the method signature.
public class Calculator {
    public int Add(int a, int b) {
        return a + b;
    }

    public double Add(double a, double b) {
        return a + b;
    }
}
  • Method overriding, on the other hand, is a form of runtime polymorphism, where a subclass provides a specific implementation of a method that is already provided by its parent class. The system determines the correct method to call at runtime, based on the actual type of the object.
public class Animal {
    public virtual void MakeSound() {
        Console.WriteLine("The animal makes a sound");
    }
}

public class Dog : Animal {
    public override void MakeSound() {
        Console.WriteLine("The dog barks");
    }
}

public class Cat : Animal {
    public override void MakeSound() {
        Console.WriteLine("The cat meows");
    }
}

Interface implementation is also a form of polymorphism, as a class implementing an interface must provide an implementation for each of the interface's methods. Here, polymorphism is manifested as the ability to interact with an object based on the more general contract defined by the interface, rather than the specific capabilities of the class.

public interface IMovable {
    void Move();
}

public class Car : IMovable {
    public void Move() {
        Console.WriteLine("The car drives");
    }
}

public class Boat : IMovable {
    public void Move() {
        Console.WriteLine("The boat sails");
    }
}

In all these forms, polymorphism provides a way to handle different types of objects (distinguished by classes or method signatures) in a uniform manner.

NoName
  • 643
  • 3
  • 8