Reputation: 35605
It looks like this overloaded constructor has itself as an interface, to create a Singleton Pattern - is that what is happening?
Is this a common constructor idiom in C#
?
class clDBaccess
{
// private field
private readonly string conn;
public clDBaccess()
: this(ConfigurationManager.ConnectionStrings["foo"].ConnectionString)
{
}
public clDBaccess(string connectionString)
{
this.conn = connectionString;
}
...
...
Upvotes: 0
Views: 200
Reputation: 2908
No, it does not fit the singleton pattern. The constructors would need to be private so that object instantiation is controlled by the class itself.
For example:
public class Singleton
{
private Singleton()
{
}
private static Singleton instance = new Singleton();
public static Singleton Instance
{
get
{
return instance;
}
}
}
Upvotes: 1
Reputation: 56727
"Singleton" means that there can only ever be one instance of a class. Typically you will find a public static
property that returns the single instance of that class.
To ensure that the class can not be instantiated more than once, the constructor(s) will typically be private.
This is not the case here. It's a normal class with two constructors, where the parameterless constructor "redirects" to the preferred constructor with a useful default value.
Upvotes: 3
Reputation: 472
No, and any proper singleton should have a protected constructor.
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Upvotes: 6
Reputation: 21661
No. The default constructor here is simply a convenience for using the connection string foo
from app.config
. There's nothing preventing multiple instances of this class from being created, but if you create them using the default constructor they'll connect to the same database (but won't necessarily be sharing the same connection).
One reason to do this is that the conn
property is readonly
- it must be initialized by the constructor (and cannot be changed after the constructor is done), and so the default constructor attempts to initialize it from a meanigful setting rather than setting it to null or string.Empty
.
Upvotes: 6
Reputation: 179264
Singleton pattern has the constructor being called once ever. This is just method overloading to provide good defaults to a parameterless constructor.
You can call the constructor and create as many instances as you'd like, so it's not a singleton.
Upvotes: 8