Saturday, September 19, 2009

Instantiating types with no public constructors

In some occasions you want to instantiate a type without a public constructor. Why should you want to do this?

For example, imagine you have a customer class in your system. One of the rules you always try to follow is that an object can never be in an invalid state. For the customer class this means that we always need at least a firstname and lastname. How can we make sure that a customer always has these two values? That's easy.

By using a public constructor that asks you to provide these two values and by readonly properties for first and lastname, you're certain that your customer object is valid.

But when your data layer is fetching customers from the database, it's far more easy to let it use a parameterless constructor than when it has to call your constructor with two parameters(in the assumption that you want to make your data layer as generic as possible). So in that case you can add a second protected constructor without any parameters. No one from outside the class can call this constructor, so developers will always use the constructor with the first and lastname parameter.

Anyway, how can you get this done? One of the overloads of the Activator.CreateInstance method makes this possible.

No comments: