Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Are there Optional Parameters for C#?

Status
Not open for further replies.

hh2424

Programmer
Feb 18, 2003
37
US
I am a VB programmer so I am quite familiar with the use for optional parameters. However, I was wondering if C# support the same thing? If not, Is there anyway around it? [ponytails]

thanks.
 
C# doesn't have optional parameters. But with it's method overloading, you don't need them. So instead of doing something like this in VB6:
Code:
Public Function LogError(ByVal lErrorNum As Long, _
                         ByVal sErrorMsg As String, _
                         ByVal sModuleName As String, _
                         ByVal sFunctionName As String, _
                         ByVal eLogDestination As LogDestinationEnum, _
                         Optional ByVal lErrorLineNum As Long, _
                         Optional ByVal sErrorData As String) As Boolean
You would do something like this:
Code:
///
///
public bool LogError(int ErrorNum,
                     string ErrorMsg,
                     string ModuleName,
                     string FunctionName,
                     LogDestinationEnum LogDestination)
{
   return LogError(ErrorNum, ErrorMsg,
                   ModuleName, FunctionName,
                   LogDestination, 0,
                   String.Empty);
}

///
///
public bool LogError(long ErrorNum,
                     string ErrorMsg,
                     string ModuleName,
                     string FunctionName,
                     LogDestinationEnum LogDestination,
                     int ErrorLineNum)
{
   return LogError(ErrorNum, ErrorMsg,
                   ModuleName, FunctionName,
                   LogDestination, ErrorLineNum,
                   String.Empty);
}

///
///
public bool LogError(long ErrorNum,
                     string ErrorMsg,
                     string ModuleName,
                     string FunctionName,
                     LogDestinationEnum LogDestination,
                     int ErrorLineNum,
                     string ErrorData)
{
   // Actual code to log errors goes here
}
What this does is allow your code to call any one of the three methods, depending on the number of parameters that you include in the call. Inside the method, all the calls get forwarded to the one with the greatest number of parameters (passing in zero, empty string, etc. for the unused values).

The only thing you've got to watch out for is if your "optional" parameters are of the same type (both string, for example), in which case the compiler can't tell them apart.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top