Bookmark and Share

Overloading Constructors

If you're using code generation, it's a good idea to remember that you can call the default constructor for a class from an overloaded constructor. This is easy to accomplish:

public Person(int age) : this()

Ron Jacobs recently discovered the necessity of doing this when he noticed his generated classes weren't functioning correctly. I'm sure it was a pain to track down the cause of the malfunctioning class. His lesson learned is a good one, "if you are creating a partial class and overload constructors it would be a very good idea to call the default ctor just like it is a very good idea to call the default base ctor from a derived class."

You can chain constructors in this way as well. This can be used to make parameters default to a value.

public Person() : this(18)
public Person(int age)

In C# 4.0 this will not be necessary, as we will finally have optional parameters.

public MyClass(int age =  18)

This can get interesting with the default constructor. Because of the betterness factor, the default constructor (if it exists) would be called instead of the version with the optional parameter if one were to instantiate the class without parameters. Keep this in mind next year when you receive that fresh copy of Visual Studio 2010.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Tag cloud

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.