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?
Asked
Active
Viewed 9.6k times
14
-
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 Answers
39
New to visual studio 2010
for example
public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
}
Richard Friend
- 15,800
- 1
- 42
- 60
-
1
-
7FWIW, no he didn't. If you read the link he provided, it's the example given by MSDN. – Joe Martella Mar 03 '17 at 19:36
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
-
Ya, the answer given by @Reddog matches with my recent search in MSDN. And the thing worked me out, when i updated my version. – Sai Kalyan Kumar Akshinthala Feb 25 '11 at 11:34
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
-
1You don't have to be using .NET 4. You just have to be using the C# 4 compiler. You can be *targeting* .NET 2. – Jon Skeet Feb 25 '11 at 11:28
-