Sunday, November 2, 2008

Getting some class in .NET: Chained contructors

This is a nifty C# way to create overloaded consturcors that need to have some parameters passed into it. Instead of passing parameters from one constructor to another and setting parameters in the code, you just pass the values to the constructor with the most logic.
Let's say that you have a formatting class with a default constructor and a overloaded one. The overloaded constructor has some extra parameters to allow uppercase switching and needs some information to perform his tasks. This is an example on how to use thsi feature.

public class FormatString
public FormatString() : this("asdf",false)

public FormatString(string str) : this (str, true)
public FormatString(string str, bool upper)
str = upper? str.ToUpper() : str;
Here you can just call the default constructor and it will print out "foo", in lowecase. What :this("foo", false)  is doing is just chaining the parameters further down to the next constructor. So if we would have called the FormatString("foo") constructor instead, we would have got "FOO", in uppercase.

Have fun and wear it out.