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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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)