How to pass optional parameters to a method in C#?
Suppose I created one method called SendCommand
public void SendCommand(string command,string strfileName)
{
if (command == "NLST *" ) //Listing Files from Server.
{
//code
}
else if (command == "STOR " + Path.GetFileName(uploadfilename)) //Uploading file to Server
{
//code
}
else if ...
}
Now I want to call this method in main method like
SendCommand("STOR ", filename);
SendCommand("LIST"); // In this case i don't want to pass the second parameter
How to achieve that?
Pre .NET 4 you need to overload the method:
public void sendCommand(String command)
{
sendCommand(command, null);
}
.NET 4 introduces support for default parameters, which allow you to do all this in one line.
public void SendCommand(String command, string strfilename = null)
{
//method body as in question
}
By the way, in the question as you have written it you aren't calling the method in your first example either:
Sendcommand("STOR " + filename);
is still using a single parameter which is the concatenation of the two strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With