Search code examples
c#constructormultiple-constructors

C# alternate parameterless constructor


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?


Solution

  • 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();