Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass optional parameters to a method in C#?

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?

like image 994
Swapnil Gupta Avatar asked Jul 29 '10 08:07

Swapnil Gupta


1 Answers

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.

like image 149
Martin Harris Avatar answered Oct 07 '22 11:10

Martin Harris