People with VB6.0 background always arguing with C# developers for some nice features like optional parameters which let you make a parameter as optional. Only need to write an Optional key word with parameter. In C# we normally handle these situations by creating numerous over loadings which will increase the size of the file. At last in version 4.0 C# also came with optional parameters along with named parameters. Below explaining all these with the help of a small customized class.
Optional Parameters and Default Values
I have a class like below. The method GetDetails will return the details based on id and name. At least you should pass id. But name is not mandatory. Before 4.0 release we are implementing this by define two methods using overloading like,
ArrayList GetDetails(string id) and ArrayList GetDetails(string id, string name)
If you need to pass both parameters you will call second method. Otherwise 1st once. I personally faced lot of junk overrides like this and thought about good old VB6.0 optional parameters. That's why now in 4.0 version you only need to declare one method like below.
public class MyClass
{
public ArrayList GetDetails(string
id, string name = "")
{
return new ArrayList();
}
}
What's the new thing here? After second parameter declaration, immediately assigning it with a value, "". So if you passed only id, name will be taken automatically with a value of "". So I can this method like below
MyClass cls = new MyClass();
//Only id passing
ArrayList list = cls.GetDetails("1");
//Both id and name passing
ArrayList list = cls.GetDetails("1",
"Jaish");
You can see I am calling only one method for both scenarios by utilizing latest 4.0 version optional parameter and default value features. More over you can identify that whether any of the parameters of a method is optional through VS 2010 editor. It's so smart that identifying such parameters and showing them with a square bracket like below screen shot.



aman gandhiPosted Feb 1, 2012, 5:22 AM
it is showing an error "Error:Default parameter specifiers are not permitted" how to resolve it.
aman gandhiPosted Jan 31, 2012, 6:36 AM
can we use optional parameter with int type variables??
Praveen RaveendranPosted Jan 25, 2011, 12:33 AM
Its very nice to have optional parameters in methods. We have the optional parameters in VB.net i guess.