Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameter in c#

Tags:

c#

c#-4.0

i am using optional parameter in the following code. but that shows error "default parameter specifiers are not permitted" anybody help me sir.

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

}
like image 698
Arul Avatar asked Nov 28 '22 02:11

Arul


1 Answers

It looks like there's some misinformation in some of the answers:

  • Optional parameters were introduced into C# 4, so you must use the C# 4 compiler
  • Optional parameters have been in the framework forever, so you can target any version of the framework and still use them, so long as you're using the C# 4 compiler. It's entirely reasonable to target .NET 2 with the C# 4 compiler, and then someone referencing your library from, say, VB8 would still be able to use your optional parameters.

As others have stated, overloads are an alternative to using optional parameters if you're not using C# 4 or if you want your code to be consumed by earlier C# code. (If you build a library using C# 4 but then some C# 3 code needs to call into it, those optional parameters are effectively going to be required as far as that code is concerned.)

(As an aside, I would seriously reconsider your names... I know this is only sample code, but generally speaking prefixes like "p" for parameters are discouraged as a matter of convention, and likewise methods are generally Pascal-cased.)

like image 79
Jon Skeet Avatar answered Nov 29 '22 17:11

Jon Skeet