tags:

views:

136

answers:

3
+1  Q: 

C# Constructor

I recently saw a C# constructor that look something like this...

public Class foo
{
    public foo() : this(new bar())
    {}
}

Can anybody help me interpret this? where does the bar() fit in?
If you could help me complete the class by inserting the bar() in its proper place so that I can compile/debug and see the whole picture.

Thanks in advance.

Nikos

+1  A: 

There will be a second constructor on class foo with a signature like this

public foo(bar Bar)
{
     ... do something with bar here;
}
MrTelly
+5  A: 

The foo class should contain another constructor, that takes a bar object as a parameter.

public class foo
{
    public foo()
        : this(new bar())
    { }
    public foo(bar b)
    {
    }
}
public class bar
{
}
Scott Ferguson
+1  A: 

This is a common technique to ensure all constructors go through a single point so you only have to change that point (it may have other uses but I'm not aware of them).

I've seen it in things that use default arguments such as:

class Rational {
    private:
        long numerator;
        long denominator;
    public:
        void Rational (long n, long d) {
            numerator = n;
            denominator = d;
        }
        void Rational (long n): Rational (n,1) {}
        void Rational (void): Rational (0,1) {}
        void Rational (String s): Rational (atoi(s),1) {}
}

Bear with the syntax, I don't have ready access to a compiler here but the basic intent is to centralize as much code as possible in that first constructor.

So if, for example, you add a check to ensure the denominator is greater than zero or the numerator and denominator are reduced using a greatest common divisor method, it only has to happen at one point in your code.

paxdiablo
Interesting. What happens with code that you put into the empty brackets?
Svante
It still runs, but after the dependency (main constructor).
paxdiablo