Optional parameters and why they make life easy
Imagine you have a simple logging framework which basically revolves around a WriteLog-method which takes at least a log message and at most a log message, a severity (debug, info, warning, error or fatal), an encoding (utf-8 by default), and a color for good measure. Now, four different parameters won’t sound like a lot, but there are actually eight different parameter combinations — if you assume that the log message is always there:
- Message
- Message and severity
- Message and encoding
- Message and color
- Message, severity and encoding
- Message severity and color
- Message, encoding and color
- Message, severity, encoding and color
Those are a lot of methods and method headers to write and your code will look like this:
What if I told you there was a better way?
Optional Parameters
Sometimes also called “default parameters”, because they’re actually the same thing. If something is optional, then there has to be some sort of value if the parameter was not explicitly given. Here’s the same code with optional parameters:
This method needs to be called with at least a string as parameter, or any combination of the other optional parameters. If none is supplied, then the value after the assignment is used. In my case, I use whatever is supplied as “Logger.Defaults”.
The catch
There has to be one, right? Sadly, yes. As MSDN states:
[…] the CLS allows compilers to ignore the values that are assigned to these parameters.
In short: While most of the C# compilers out there will do just as told, there may be some non-mainstream compilers which ignore the default parameters and give you weird exceptions. If you’re using the standard VS compiler, you should be fine. Mono should be fine too! All in all, you should be fine if you do that, just be aware that there is a possibility of problems.