How to????

iebidan

Contributor
Joined
Feb 6, 2003
Messages
484
This is the first time I try in C#, so I don't know how to do it, here is the problem
In VB.NET you can specify optional arguments for a function (example code), how you do it in C#

Visual Basic:
Public Function FUNCTIONNAME (Optional ByVal VARIABLE as String = "")
' The code goes here
End Function

How you do the Optional argument in C#????
Thanks for the help
 
You don't. Instead, create mutliple overloads of the same
function, with the optional parameters missing for some.

First create the main function which does all the calculating in it,
and it has all the parameters you're going to use. Then write
overloads that have less parameters and pass default values to
the parameters that are missing.

For example:

C#:
public string FunctionName() {
  return FunctionName("default value 1", "default value 2");
}

public string FunctionName(string parameter1) {
  return FunctionName(parameter1, "default value 2");
} 

public string FunctionName(string parameter2) {
  return FunctionName("default value 1", parameter2);
}

public string FunctionName(string parameter1, string parameter2) {
  // Do the actual processing of the parameter here
}
 
Just to be petty but the two functions
C#:
public string FunctionName(string parameter1) {
  return FunctionName(parameter1, "default value 2");
} 

public string FunctionName(string parameter2) {
  return FunctionName("default value 1", parameter2);
would be detected as being the same because they both only accept a single string.
 
Yeah, I got the idea, I'm on that right now, getting a headache this early but hey, that's why we love our jobs
Thanks guys
 
Use variable length parameters for a function. Ex:

Code:
	public void MethodName(params object[] list)
		{}

Then you can check how many parameters were passed to the method.

Kendal
 
Using an array of parameters can be handy if you really don't know how many parameters are going to be provided, however it may require a lot of runtime type checking and casting if you only pass them in as objects.
Overloads allow you to define several version all of which are strongly typed and generate sensible tooltips in the IDE to make it easier for developers to see the names and types of parameters involved.

I personally prefer overloaded functions and tend to follow the MS standards of providing overloaded functions for 1,2 or 3 optional parameters and if more are required also providing a version that accepts an object array. eg see
Console.WriteLine
and it's overloads involving one, two, three and many objects.
 
Last edited:
Back
Top