0

i need to have a function that has two arguments.

public void funx(string a, string b)
{
 // operations using string a and b
}

is it by any way possible to call the method funx() with only the first argument 'a' . if second argument 'b' is not entered during the function call, it should take a default value (for b) that can be set in fun x. in case i call funx() with two arguments a & b , then the values that i have provided in the function call should be used while skipping the default values set( for 'b').

in simple words, 'b' is optional. if entered, its value should be used. if not entered, then a default value should be used

user2864740
  • 60,010
  • 15
  • 145
  • 220
God_Father
  • 491
  • 3
  • 8
  • 17

2 Answers2

3

Sure, like this:

public void funx(string a, string b = "default value")
{ 
   // operations using string a and b
}

If you give a default value to b then you are making it optional so you can call your method with providing one argument.If you don't provide a value for b then default value will be used, if you provide a value then default value will be ignored.

Also default value of an optional parameter has to be a compile-time constant and optional parameters are defined at the end of the parameter list. You can refer to documentation for more details.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • thank mate, this helped.. incase I provide a value for 'b' in the function call will that be used or will the default value be used – God_Father Apr 18 '14 at 21:21
  • @God_Father: The default will of course be overwritten with what you pass in. – Magus Apr 18 '14 at 21:21
0

Yes it's possible by

public void funx(string a, string b = "")
{

}

But I would prefer to overload the function like:

public void funx(string a)
{
   this.funcx(a, "default");
}

public void funx(string a, string b)
{
 // operations using string a and b
}
Tomtom
  • 9,087
  • 7
  • 52
  • 95