30 May 2010 Ferado

C# 4.0 & Optional Parameters

When writing a method in .NET (C# or VB), you typically have to overload that method if you want to provide default or optional parameters. Now, thanks to C# 4.0 and VB 10, you can use optional parameters.

For example, prior to C# 4.0, you had to do the following:

[cc lang=”c#”]
// Assume we’re using a class and the following stuff is from our class

// no parameters
public void myMethod()
{
myMethod(“optional”);
}

// one parameter
public void myMethod(string str)
{
// STUB
}
[/cc]

As you can see from the preceding code, you need to type more than one function. To each their own. Some people like doing this, some people don’t. I like how it works in PHP:

[cc lang=”php”]
function myFunc($optional=”hello world!”) {
// STUB
}
[/cc]

Even better, Python let’s you do this:

[cc lang=”python”]
def myFunc(str1=”something”, str2=”something else”):
print str1, str2

# usage:
myFunc(str2=”Something new”)

# prints out
something Something new
[/cc]

In C# 4.0, you can do something similar to the way PHP does it, like so:

[cc lang=”c#”]
public void myMethod(int i = 1, double awesome = 3.0)
{
// STUB
}
[/cc]

Conclusion

You’ve now just learned how in the new .NET (check this post’s date) allows you to use optional parameters to cut down on your code so that you don’t have to overload your methods anymore, unless you want to. You’re going to need this in your toolbox. Note, please use overloading when you need to. There might be a time when you need to overload in order to keep your code looking cleaner. The choice is yours. Use responsibly.