Optional parameter in C #

I am using an optional parameter in the following code. but it shows the error "parameter specifiers are not allowed by default", someone help me sir.

public void getno(int pvalu, string pname = "") { } 
+4
source share
5 answers

Some answers seem to have some misinformation:

  • More options were introduced in C # 4, so you should use the C # 4 compiler
  • The optional parameters were in the structure forever, so you can target any version of the framework and use them as long as you use the C # 4 compiler. It is advisable to target .NET 2 to the C # 4 compiler, and then someone refers to your a library, for example, VB8 will still be able to use your optional parameters.

As others noted, overloads are an alternative to using optional parameters if you are not using C # 4 or want your code to be used by earlier C # code. (If you are creating a library using C # 4, but then you need to call the C # 3 code, these optional parameters will really be needed for this code.)

(Aside, I would seriously review your names ... I know that this is just a code example, but in general, prefixes such as "p" for parameters are discouraged as conditional, and similar methods are usually Pascal-cased.)

+24
source

Try overloading the method sooner

  public void getno(int pvalu) { getno(pvalu, ""); } public void getno(int pvalu, string pname) { } 

See Method Recommendations

See also .Net 4 Named and Optional Arguments (C # Programming Guide)

+7
source

Additional options have been added in C # 4.0: which version are you using?

VB.NET always had optional parameters.

You can always use overloads and a chain of methods to get similar capabilities:

 public void getno(int pvalu) { getno(pvalue, ""); } public void getno(int pvalu, string pname) { } 
+2
source

Are you planning a .NET 4 compiler (for example, VS 2010), since only this compiler supports additional parameters for C #?

Personally, I would overload this method, and not use the optional parameters for the methods that I created, reserving using additional parameters for use with API calls, where there are a large number of default values.

Thanks to Jon Skeet for clarifying the difference between targeting .NET 4 and using the .NET 4 compiler.

+1
source

Additional parameters are supported in C # from version 4, make sure that your project is configured to compile using the C # 4 compiler.

0
source

All Articles