Reputation: 109
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
Upvotes: 1
Views: 562
Reputation: 881093
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.
Upvotes: 1
Reputation: 7830
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
{
}
Upvotes: 7
Reputation: 14865
There will be a second constructor on class foo with a signature like this
public foo(bar Bar)
{
... do something with bar here;
}
Upvotes: 1