Visual Studio .NET - a parameter optional - Asked By pikouta pikouta on 09-Feb-12 08:34 AM

Please how can i  make a parameter optional in visual studio.
Amit Choudhary replied to pikouta pikouta on 09-Feb-12 08:40 AM
yes , in c# if you will declare like as
     public void ExportReport(string templatePath , bool isSave = false)

Then isSave will be work as optional you can call it as ExportReport("c:\temp")
But this is available in .Net frame work 4.0.
dipa ahuja replied to pikouta pikouta on 09-Feb-12 08:53 AM
Optional Argument : The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. Default values must be constants.
For ex:
class B
  Public void getCountry(string Country="India")
Here to call this method you have to pass a string variable, But as you can see it is assigned a value India, That means this is optional argument. It means if you pass any string then it will take that string. But if u don't pass then the country variable will contain India
For Ex:
B b1 = new B();
b1.getCountry("Canada"); //take country as Canada
b1.getCountry(); //Take country as Default value that is india
D Company replied to pikouta pikouta on 09-Feb-12 08:55 AM
Hello Friend,

Optional parameters are indicated by the Optional keyword in the procedure definition. Every optional parameter in the the things that u have take care are it  must have  a default value. and The default value for an optional parameter must be a constant expression. and the last constraint is Every parameter following an optional parameter in the procedure definition must also be optional.

public  void OptionalFunction(string name, [Optional, DefaultParameterValue("")] string id, [Optional, DefaultParameterValue("")] )
//ur business logic


Hope it cleares to you!!
pikouta pikouta replied to D Company on 09-Feb-12 09:21 AM
Tank 's for your replay .
if I have understood one optional parameter must have a default value. but what I want is that if the onscreen user does not enter the parameter, the report brings back all the record without filter on this parameter.

Kind Regard,
D Company replied to pikouta pikouta on 09-Feb-12 12:21 PM
So, in that case you have to set your default value like "All" or something which would be able to fetch all the values.

Hope its clear to you!!