14

I am using a method for doing some action, i want the method to be written only once by using Optional Parameters in C#, other than Method Overloading is there any?

  • there may be a lot of issues which can occur if you are changing the signature of a function without overloading.http://stackoverflow.com/questions/3914858/can-i-give-default-value-to-parameters-in-c-sharp-functions – kbvishnu Apr 05 '13 at 05:47

5 Answers5

39

New to visual studio 2010

named and optional arguments

for example

public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
}
Richard Friend
  • 15,800
  • 1
  • 42
  • 60
15

Have a look at following code

Library to use

using System.Runtime.InteropServices;

Function declaration

private void SampleFunction([Optional]string optionalVar, string strVar)
{
}

And while giving call to function you can do like this

SampleFunction(optionalVar: "someValue","otherValue");

OR

SampleFunction("otherValue");

Reply if it helps.!:)

Akshay
  • 1,831
  • 1
  • 18
  • 22
9

Yes, use optional parameters (introduced in C# 4).

public void ExampleMethod(int required, string optionalstr = "default string",
    int optionalint = 10)

When you provide a default value to a formal parameter, it becomes optional.

For prior versions, overloads are the only option.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
4

They have been introduced in C# 2010 (that is generally VS2010 with Framework 4.0). See Named and Optional Arguments (C# Programming Guide).

In previous C# versions you're stuck with overloads (or param arrays).

Reddog
  • 15,219
  • 3
  • 51
  • 63
2

If you use C# 4.0 it is.

You can then define your method like this:

public void Foo( int a = 3, int b = 5 ){
  //at this point, if the method was called without parameters, a will be 3 and b will be 5.
}
Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151