Reputation: 141
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 = "")
{
}
Upvotes: 4
Views: 7260
Reputation: 57548
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.
Upvotes: 1
Reputation: 499302
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)
{
}
Upvotes: 2
Reputation: 11608
Optional parameters are supported in C# from version 4, make sure your project is set to compile using the C# 4 compiler.
Upvotes: 0
Reputation: 1503180
It looks like there's some misinformation in some of the answers:
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.)
Upvotes: 25
Reputation: 166516
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)
Upvotes: 7