Using Default Values in C# 4.0

One of the new features of C# 4.0, the new version of C# included in Visual Studio 10 beta, is the use of default values.
If you are on the road long enough to be a C++ programmer, you will remember that default values was one of the features of member functions in C++. Quickly stated, a default value in a member function can be used to provide a value for an argument when it is not introduced by the calling code.
Having default values saves some time when writing code because you don’t need to type standard values for arguments that are rarely used.

Problems With Default Values

Default values, however, are not without their problems. First, the use of a default value can lead to confusion when creating methods. Suppose for example that you have two methods:

void f(int a, int b=0) { }
void f(int a) { }

This may trigger a compile time error, because there may be an ambiguity when using f with only one argument.
The worse problem in C++, however, is that the value of the constant (in this case 0) is not guaranteed to be the same between definitions of f in the base class and derived classes. This is a big problem that C++ users are still trying to solve today.

C# implementation

The advantage of C# in this issue is that, having a smaller compiler, they can make it much smarter. For example, the C# compiler will always give precedence to methods that have no default arguments, so there is less possibility for confusion.
Despite this, we should try to avoid default values in methods whenever possible. Default values can still make your code confusing and hard to maintain.
To avoid this kind of confusion, for example, you can try to get rid of methods with parameters that are used only some times. One way of doing this is creating separate methods for different cases. Also, you should give different names to methods. For example:

void FuncWithExtraArg(int a, int b) { }
void Func(int a) { }

is a better way to name the methods described above, so we don’t need to use a default argument.
Default arguments were added to C# to simplify coding for Excel and Word, where method have a lot of parameters of this kind. If you don’t need this feature, however, you probably should avoid default arguments altogether, and use them only when really necessary.

Similar Posts:

About the Author

Carlos Oliveira holds a PhD in Systems Engineering and Optimization from University of Florida. He works as a software engineer, with more than 10 years of experience in developing high performance, commercial and scientific applications in C++, Java, and Objective-C. His most Recent Book is Practical C++ Financial Programming.

One Response to “Using Default Values in C# 4.0”

  1. “having a smaller compiler, they can make it much smarter” huh ?

    By Me on Dec 12, 2011

Post a Comment