Optional parameter declaration and default values

I

Imran Aziz

Hello All,
I am new to C# , how can I delare parameters to a function as optional,
and also how are default values assigned ?

consider the function

public String myFunc(String thisisOptional, String OptWithDefaultValue)
{

}

Imran.
 
M

Mark Rae

I am new to C# , how can I delare parameters to a function as optional,

You don't - you use overloads.

public string myFunc()
{
/*
do something
*/
}

public string myFunc(string thisisOptional)
{
/*
do something with thisisOptional
*/
string newString = myFunc();
}
 
I

Imran Aziz

I see, it means there is no way to declare optional function parameters in
C#, strange , no doubt I was not able to find it in the documentation :)

Thanks a lot.

Imran.
 
F

Franco, Gustavo

You can't.

Use:
1) Overloads
public String myFunc()
{
myFunc(null, x //default value);
}

public String myFunc(String thisisOptional)
{
myFunc(thisisOptional, x //default value);
}

public String myFunc(String thisisOptional, String OptWithDefaultValue)
{
..... code here.
}

2) params object[] parameters like parameter in the method.

public String myFunc(params string[] parameters )
{
String thisisOptional = null;
String OptWithDefaultValue = defaultValue;

if (params.Lenght >= 2)
{
thisisOptional = parameters[0];
OptWithDefaultValue = parameters[1];
}
else if (params.Lenght == 1)
thisisOptional = parameters[0];

.... code here
}

Gustavo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top