Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to call a private constructor from a public one

Tags:

c#

ado.net

I want to be able to instaniate a class with a public constructor that will by default call a private constructor and I think it is something close to the code below, but it isn't.

    public MySQLConnector()
        : this MySQLConnector (ConfigurationManager.AppSettings["DBConnection"])
    {
    }

    private MySQLConnector(string dbConnectionString)
    {
        //code
    }
like image 618
Recursor Avatar asked Nov 14 '13 07:11

Recursor


1 Answers

You've almost got it. Just use this(...), without the class name:

public MySQLConnector()
    : this(ConfigurationManager.AppSettings["DBConnection"])
{
}

This is documented in Using Constructors (C# Programming Guide):

A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression.

like image 156
p.s.w.g Avatar answered Oct 29 '22 10:10

p.s.w.g