Warning: Cannot modify header information - headers already sent by (output started at /home/jtolle/public_html/blog.kyletolle.com/index.php:1) in /home/jtolle/public_html/blog.kyletolle.com/wp-includes/feed-rss2.php on line 8
Thoughts of an Eaten Sun » Constructor http://blog.kyletolle.com Kyle Tolle of nullSIX - Technology, science, goings-on of the world, and anything else that interests my thought-process model. Wed, 20 May 2009 05:49:18 +0000 http://wordpress.org/?v=2.9.2 en hourly 1 Call One Constructor from Another in C# http://blog.kyletolle.com/call-one-constructor-from-another-in-csharp/ http://blog.kyletolle.com/call-one-constructor-from-another-in-csharp/#comments Fri, 30 Jan 2009 08:42:49 +0000 Kyle Tolle http://blog.kyletolle.com/?p=53 I am working on an assignment for Professor Cawfis’ C#/.NET class I am taking this quarter at The Ohio State University.</plug> The assignment asks us to write a hierarchy of Tanks for a water plant. For a specific tank, we want a constructor that will take a parameter volume. But we also want to have a parameterless constructor that will create a tank with a default volume for the tanks in this system.

Here’s what we initially have:

using Liter = System.Single

namespace KyleTolle.Tanks
{
    class Tank: TankBase
        {

            public Tank()
            {
                // Want this to create a tank of a default volume.
            }

            public Tank(Liters maximumVolume)
            {
                this.Volume = maximumVolume;
            }
    }
}

All we need to do to have the parameterless constructor create a tank with a default value is have it call the other constructor, passing in a default value for the volume. But how do we do that?

It’s simple. To call another constructor in this class, we just add a bit more code before the method’s body braces:

public TypeConstructor(): this (parameters) { }

Want to call a constructor in the base class? Just change the previous example to say “base” instead of “this”:

public TypeConstructor(): base (parameters) { }

This could be helpful if the parent class has a constructor with the desired behavior.

So to call another constructor in our Tank example, we end up with:

using Liter = System.Single

namespace KyleTolle.Tanks
{
    class Tank: TankBase
        {

            public Tank() : this(100F)
            {
                // This creates a tank with a default volume.
            }

            public Tank(Liters maximumVolume)
            {
                this.Volume = maximumVolume;
            }
    }
}

I decided to write this post because it wasn’t immediately apparent to me how to call one constructor from another. Google did lead me to the solution, but I give a bit more concrete example of what this can be used for.

See Also:
C# FAQ: How can one constructor call another

]]>
http://blog.kyletolle.com/call-one-constructor-from-another-in-csharp/feed/ 0