using System; class Log { public Log(string fileName) { // Open fileName and seek to end. } public void WriteEntry(string entry) { Console.WriteLine(entry); } public void WriteEntry(int resourceId) { Console.WriteLine ("Retrieve string using resource id and write to log"); } } class Overloading1App { public static void Main() { Log log = new Log("My File"); log.WriteEntry("Entry one"); log.WriteEntry(42); } }
A second scenario in which method overloading is helpful is when you use constructors, which are essentially methods called when an object is instantiated. Let's say you want to create a class that can be constructed in more than one way-for example, one that takes either a file handle (an int) or a file name (a string) to open a file. Because C# rules dictate that a class's constructor must have the same name as the class itself, you can't simply create different method names for each of the different variable types. Instead, you need to overload the constructor: -
using System; class File { } class CommaDelimitedFile { public CommaDelimitedFile(String fileName) { Console.WriteLine("Constructed with a file name"); } public CommaDelimitedFile(File file) { Console.WriteLine("Constructed with a file object"); } } class Overloading2App { public static void Main() { File file = new File(); CommaDelimitedFile file2 = new CommaDelimitedFile(file); CommaDelimitedFile file3 = new CommaDelimitedFile("Some file name"); } }
One important point to remember about method overloading is that each method's argument list must be different. Therefore, the following code will not compile because the only difference between the two versions of the Overloading3App.Foo method is the return type: -
using System; class Overloading3App { void Foo(double input) { Console.WriteLine("Overloading3App.Foo(double)"); } // ERROR: Only differs by return value. Won't compile. double Foo(double input) { Console.WriteLine("Overloading3App.Foo(double) (second version)"); } public static void Main() { Overloading3App app = new Overloading3App(); double i = 5; app.Foo(i); } }