So I'm just thinking about function overloading...
Overloaded methods share the same name but have a unique signature. The number of parameters, types of parameters or both must be different. A function can't be overloaded on the basis of a different return type alone.
So in the following example, why overload setName
rather than use optional parameters for the middle and last name values?
class funOverload
{
public string name;
//overloaded functions
public void setName(string last)
{
name = last;
}
public void setName(string first, string last)
{
name = first + "" + last;
}
public void setName(string first, string middle, string last)
{
name = first + "" + middle + "" + last;
}
//Entry point
static void Main(string[] args)
{
funOverload obj = new funOverload();
obj.setName("barack");
obj.setName("barack "," obama ");
obj.setName("barack ","hussian","obama");
}
}
At the very least, using the following would cut down on the amount of code that needs to be written:
public void setName(string first, string middle = "", string last = "")
{
name = first + "" + middle + "" + last;
// name = "barack" + "" + "";
}
//Entry point
static void Main(string[] args)
{
funOverload obj = new funOverload();
// could optionally set middle and last name values here as well
obj.setName("barack");
}
I understand the concept of overloading, but I what I don't get is why it would be a more desirable option than using optional parameters (or vice versa).
Can anyone explain?
Just for reference, here's the first function I ever overloaded: http://pastebin.com/ynCuaay1
This function allows you to call MySqlContext.GetReader()
with or without a list of parameters... I thought it made the code a lot neater than having to call GetReader(sql, args.ToArray())
all the time