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?
Use the params attribute:
public void SendCommand(String command, params string[] strfilename)
{
}
then you can call it like this:
SendCommand("cmd");
SendCommand("cmd", "a");
SendCommand("cmd", "b");
or if you use C# 4.0 you can use the new optional arguments feature:
public void SendCommand(String command, string strfilename=null)
{
if (strfilename!=null) ..
}