Before I begin I want to state that this post is intended for those who are unaware of the flexibility that overloading functions can provide, power developers can feel free to move along or provide feedback.
Assume you want to pass an optional parameter to a method, VB makes this really easy by the use of the OPTIONAL keyword:
Public Function MyFunction(ByVal parameter1 as string, Optional parameter as integer)
End Function
Very easy.
Unfortunately C# does not support the OPTIONAL keyword. So we have overloaded methods to the rescue! An overloaded method is simply a method with the exact same name as an existing method, however it has a different parameter list (aka signature). Here's a brief example:
public void MyFunction(string FirstName)
{
Console.Write(FirstName);
}
public void MyFunction(string FirstName, string LastName)
{
Console.Write(FirstName);
Console.WriteLine(LastName);
}
Notice that the method name is duplicated, and the parameter signature is different. Now when you are accessing that method Intellisense will have the little arrows to show you the different signatures denoting there is at least one overloaded method available.
This example however stinks.
There is duplicate logic there, and now it's more difficult to maintain. Here's where chaining overloaded methods really gets cool. Let's assume that LastName is optional. Let's move all our code into the most well defined method and chain the methods above it. Let me show you what I mean:
public void MyFunction(string FirstName)
{
MyFunction(FirstName, "");
}
public void MyFunction(string FirstName, string LastName)
{
Console.Write(FirstName);
Console.WriteLine(LastName);
}
Now if we call MyFunction and only pass it the first parameter, it will take that parameter and pass it and a second empty string to the version of the method that has two parameters. This is a highly simplified example, but hopefully it will show you how you can extend some of your existing behavior without having to rip your application apart. In fact this post came about because I was lamenting that the application I was fixing is an ASP classic app and I was thinking how convenient it would be if I could use optional parameters. Sure you could use the array method and all like that, which is fine if you started that way, but it adds a lot of work if you are retrofitting your function to use an array.
Not a ground breaking post, but hopefully eyeopening to either newer developers or those making the switch from VB to C#.