CSharp – Static Polymorphism – Function Overloading
Polymorphism is a Greek word that means “many-shaped”
With Function Overloading you can have multiple definitions for the same function name in the same scope.
Same name for the function, many-shaped variables.
using System; namespace ConsoleApplication1 { class Printdata { void print(int i) { Console.WriteLine("Printing int: {0}", i); } void print(double f) { Console.WriteLine("Printing float: {0}", f); } void print(string s) { Console.WriteLine("Printing string: {0}", s); } static void Main(string[] args) { Printdata p = new Printdata(); // Call print to print integer p.print(5); // Call print to print float p.print(500.263); // Call print to print string p.print("Hello C++"); Console.ReadKey(); } } }
The result is:
Printing int: 5
Printing float: 500.263
Printing string: Hello C++
For italian people: come funziona?
C# distingue automaticamente la funzione chiamata in base alle variabili che gli vengono spedite, quindi:
p.print(5); -> void print(int i)
p.print(500.263); -> void print(double f)
p.print(“Hello C++”); -> void print(string s)