C# alternate parameterless constructor

1.5k views Asked by At

Is it possible to define an alternate parameterless constructor for a C# class?

In other words, I have a class Foo. I want to have a default constructer Foo() and another constructor SpecialFoo(). I don't mind if the SpecialFoo() constructor calls the Foo() constructor.

Can I do that?

3

There are 3 answers

0
MarcinJuraszek On BEST ANSWER

You can only have one constructor with given set of parameters, so you can't have two parameterless constructors.

You can have another public static Foo SpecialFoo method, which will be factory method and will return new instance of Foo class, but to use it you won't use new keyword:

class Foo
{
    public static Foo SpecialFoo()
    {
        return new Foo();
    }
}
var instance1 = new Foo();
var instance2 = Foo.SpecialFoo();
2
p.s.w.g On

Constructors, like methods, cannot have overloads with identical parameter lists. You can, however create a static factory method, like this:

public class Foo
{
    public static Foo SpecialFoo() {
         ...
    }
}

And call it like this:

var foo = new Foo();
var specialFoo = Foo.SpecialFoo();

An alternative is to use a separate constructor like this:

public class Foo
{
    public Foo(bool special) : this() {
         if (special)
         {
             ...
         }
    }
}

And call it like this:

var foo = new Foo();
var specialFoo = new Foo(true);

Of course, this doesn't actually qualify as an 'alternate parameterless constructor' but it has some benefits over the static factory. Primarily, you can use and extend it in an inherited class, which is something that the factory method does not allow*.

* Actually, you can, but you need to hide the base factory method with new, or you will get a warning, and it's generally bad practice to hide static members on base classes.

4
Dmitry S. On

You can do this:

public class Foo
{
    public Foo()
    {
        // do something
    }
}

public class SuperFoo : Foo
{
    public SuperFoo() : base() // call the Foo constructor - you do not have to call base explicitely, just a more verbose example
    {
        // do something else
    }
}