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?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With