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 pnam开发者_运维问答e = "")
{
}
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.)
Try overloading the method rather
public void getno(int pvalu)
{
getno(pvalu, "");
}
public void getno(int pvalu, string pname)
{
}
Have a look at Method Usage Guidelines
See also for .Net 4 Named and Optional Arguments (C# Programming Guide)
Optional parameters have been introduced in C# 4.0 - what version are you using?
VB.NET has always had optional parameters.
You can always use overloads and method chaining to gain similar capabilities:
public void getno(int pvalu)
{
getno(pvalue, "");
}
public void getno(int pvalu, string pname)
{
}
Are you compiling with the .NET 4 compiler (e.g. VS 2010) as only this compiler supports optional parameters for C#?
Personally I would overload the method rather than use optional parameters for methods that I was creating, reserving using optional parameters for use with API calls where there is a large number of default values.
Thanks to Jon Skeet for clarifying the difference between targeting .NET 4 and using the .NET 4 compiler.
Optional parameters are supported in C# from version 4, make sure your project is set to compile using the C# 4 compiler.
精彩评论