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

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.


Check C# 4.0 Optional Parameters.

Also make sure you are using .NET 4.

If you need to use older versions of .NET.

Method overloading is the solution :

public void SendCommand(String command)
{
    SendCommand(command, null);
    // or SendCommand(command, String.Empty);
} 

public void SendCommand(String command, String fileName)
{
    // your code here
} 

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) .. 
}

The obvious answer for this should be, don't do it that way.

You should either have a separate method for each command, or a command base class and a separate derived class for each command, with an Execute method.

It's bad design to have one method that handles every conceivable command.

You really don't want one Sendcommand() to handle every possible command.