C# singleton definition - c#

I saw implementation like that:
class MyClass
{
private static readonly MyClass _instance = new MyClass();
public static MyClass Instance{
get{ return _instance; }
}
}
Why not make it simple?
class MyClass
{
public static readonly MyClass Instance = new MyClass();
}

You can expose public fields like this - but I prefer not to. If you leave it as a property, you can change the implementation later. For example, suppose you later add a static method which you want to be able to call without initializing the singleton - with the property version, you could change the code to:
public sealed class MyClass
{
public static MyClass Instance { get { return InstanceHolder.instance; } }
private MyClass() {}
private static class InstanceHolder
{
internal static readonly MyClass instance = new MyClass();
}
public static void Foo()
{
// Calling this won't initialize the singleton
}
}
(With the original version, the singleton might be initialized, or it might not be - it's up to the CLR.)
That's just one example of why you might want to change the implementation later. With a property, you can do that - with a field, you can't.

What you've got there would work fine, but public fields are usually frowned upon in favour of Properties. You can change the implementation of the get { ... } without needing to change calling code. This would enable you to (for example) switch to lazy initialisation where the Instance is only created the first time it is used.
Note that although the calling code wouldn't need to change, it would change the signature of your class since a readonly property is different to a readonly field.

Related

Static constructor - Singleton Design pattern in c#

What if, I replaced private constructor with a static constructor in singleton Design pattern?
public sealed class Singleton
{
private static Singleton instance=null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
Static constructor will be called only once and I couldn't find any difference in the implementation. Can we replace private with static constructor?
All that the private constructor is really doing in this case is preventing anything outside of the class from instantiating an instance of class Singleton, which is almost certainly intentional as a singleton should only have a single instance.
Static class constructors are run once for a type, at an unknown time, before the type, or any of it's static members, is to be utilized. Static fields are initialized before the static constructor would be run.
So, I suppose you could replace the constructor with a static one, but that would then give you the implicit parameter-less constructor on the Singleton Type, which would allow anyone to instantiate an instance, which is likely at odds with why you are using the singleton pattern in the first place. It also wouldn't change anything about how your class was being constructed, really, so why do it?
Take the following class as an example:
public class Test { }
Under the covers, because there is no declared constructor, the C# compiler implicitly adds a parameterless, public constructor to the class, allowing consumers to create an instance.
public class Program {
public static void Main() {
var test = new Test();
}
}
This is all fine and good if you want to be able to make instances of your class. The singleton pattern intends to only provide a single instance of a type to the consumers. We could add this static instance to our test type like so:
public class Test { public static Test Instance {get;} = new Test(); }
and we would be able to get this static instance like so:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // less than ideal
}
}
So we are providing access to our singleton object through it's instance field, as expected, but we can still create instances of the singleton type, which is less good, as it goes against the purpose of a singleton (namely, having only a single shared instance.)
So we add a private, parameterless constructor to the type.
public class Test {
private Test() {}
public static Test Instance {get;} = new Test();
}
Adding a constructor to a type will cause the C# compiler not to add an implicit public parameter-less constructor. Making it private allows it to be accessed within the class scope, which is used for instantiating our instance property, and prevents anything else from instantiating the object. The end result being:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // Compile time error
}
}
Your singleton object now prevents other instances of the class from being instantiated, and the only way to use it is through the instance property as intended.
In simple terms, if you remove the private constructor, then anyone will be able to create a new instance of Singleton:
// With the private constructor, the compiler will prevent this code from working.
// Without it, the code becomes legal.
var newInstance = new Singleton();
And if anyone can instantiate Singleton as above, then you no longer have a singleton.
Another cleaner way to do it is to use readonly on you private instance.
This is less code and also thread safe. The CLR takes care of everything for you, no need for lock , check for null and stuff.
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
public static Singleton Instance {
get {
return _instance;
}
}
private Singleton()
{
}
}
Then simply test:
[TestMethod]
public void IsSingleton()
{
Assert.AreSame(Singleton.Instance, Singleton.Instance);
}
EDIT:
example using lock
public sealed class Singleton
{
private static readonly object _lock = new object();
private static Singleton instance = new Singleton();
public static Singleton Instance
{
get
{
lock(_lock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
private Singleton()
{
}
}
In simplest terms, if you remove private, the default public constructor will get exposed. Then outsiders will be allowed to use new Singleton(); and make number of instances of Singleton class. So no Singleton Pattern will be there.
Additionally this classic implementation of Singleton pattern (private constructor + static getInstance() with either lazy-loading or eager loading) is so evil. In modern day you must switch to a Dependency-Injection framework instead.
This should work just fine. You could also make the class static and generic so you can store whatever kind of value in instance you want it to hold. This would facilitate the separation of concerns, keeping the singleton pattern and the class that it will contain separate.

How to pass parameter to static class constructor?

I have a static class with a static constructor. I need to pass a parameter somehow to this static class but I'm not sure how the best way is.
What would you recommend?
public static class MyClass {
static MyClass() {
DoStuff("HardCodedParameter")
}
}
Don't use a static constructor, but a static initialization method:
public class A
{
private static string ParamA { get; set; }
public static void Init(string paramA)
{
ParamA = paramA;
}
}
In C#, static constructors are parameterless, and there're few approaches to overcome this limitation. One is what I've suggested you above.
As per MSDN, A static constructor is called automatically to initialize the class before the first instance is created. Therefore you can't send any parameters.
CLR must call a static constructor, how will it know which parameters to pass it?
So don't use a static constructor.
Here's the work around for your requirement.
public class StaticClass
{
private int bar;
private static StaticClass _foo;
private StaticClass() {}
static StaticClass Create(int initialBar)
{
_foo = new StaticClass();
_foo.bar = initialBar;
return _foo;
}
}
Static constructors have the following properties:
A static constructor does not take access modifiers or have parameters. A static constructor is called automatically to
initialize the class before the first instance is created or any
static members are referenced.
A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary
method.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for
the lifetime of the application domain in which your program is
running.
If by "HardCodedParameter" you really mean hard coded, you can use constants.
public static class YoursClass
{
public const string AnotherHardCodedParam = "Foo";
}
public static class MyClass
{
private const string HardCodedParam = "FooBar";
static MyClass()
{
DoStuff(MyClass.HardCodedParam);
DoStuff(YoursClass.AnotherHardCodedParam);
}
}
Also, you can use static readonly properties.
Constructors on non-static class have have the benefit to ensure they're properly initialized before they're actually being used.
Since static classes don't have this benefit, you have to make ensure that yourself.
Use a static constructor with an obvious name, then in the relevant portion of your static procedures check to make sure the initialization has been performed.
The example below assumes your want to "initialize" your static class with a Form object.
public static class MyClass
{
private static Form FormMain { get; set; }
public static void Init(Form initForm)
{
FormMain = initForm;
}
private static bool InitCheck()
{
return FormMain != null ? true: false;
}
public static void DoStuff()
{
if (InitCheck())
{
// Do your things
}
else
{
throw new Exception("Object reference not set to an instance of an object");
}
}
}

Risk by using a static property in a multi-threading (or web) c# project

i am a little confused by multi-thread access risk on a static property in C#.
public class MyClass
{
public static MyClass Static
{
get
{
var c = new MyClass();
c.SomeProperty = "12345";
c.OtherProperty = DateTime.Now.ToString();
return c;
}
}
}
This example class provides a static property that create a new instance of MyClass,
like a method:
public class MyClass
{
public static MyClass Static()
{
var c = new MyClass();
c.SomeProperty = "12345";
c.OtherProperty = DateTime.Now.ToString();
return c;
}
}
Obviously, this property is not a "storage" box for an instance of MyClass, but it behaves like a static method (that, if i reading good a msdn article, is completely thread-safe).
My question is: i risk something with using this concept ?
Especially in a web or multi-thread enviroinment ?
There is a no particular utility in using it, only for simple reading and cleaning code:
MyClass.Static.SomeProperty = "Something";
is more clear than
MyClass.Static().SomeProperty = "Something";
All help will be appreciated
Thanks
In both your examples you're returning a new instance of MyClass every time the property is accessed. There is no danger that you'll have any concurrency issues when multiple threads access the static property method at the same time, because they're actually modifying the properties of their own instance of MyClass and not sharing it between them.
If you had something like this instead:
public class MyClass
{
private static MyClass _myClass;
public static MyClass Static
{
get
{
return _myClass ?? (_myClass = new MyClass());
}
}
}
...then you'd cause problems when two threads attempted to write/read properties of the resulting MyClass instance, because they're operating on the same MyClass reference _myClass.
Even so, there are two issues with the code you've posted:
You need to change it to a method and rename it, because it's actually creating something, not accessing a static version of anything. Then you can operate on the return value. Something like this:
public class MyClass
{
public static MyClass Create()
{
var c = new MyClass();
c.SomeProperty = "12345";
c.OtherProperty = DateTime.Now.ToString();
return c;
}
}
Then use it like this:
var myClass = MyClass.Create();
myClass.SomeProperty = "Stuff";
The way you're setting properties currently means their values aren't persisted, because a new MyClass is created the next time the Static property is accessed.
If when you set SomeProperty you actually want a static instance to be updated you'll need to lock on a static object to solve the multi threading issue - something like this:
public static class MyClass
{
private static readonly object locker = new object();
private static string someProperty;
public void SetSomeProperty(string val)
{
lock (locker)
{
someProperty = val;
}
}
public void GetSomeProperty()
{
lock (locker)
{
return someProperty;
}
}
}
It seems that you are creating a static factory method that will give you a fully instantiated object.
Threading would not be an issue here because every time you call this method or property you are creating a new object. If 2 threads call the same method at the same time they will each keep on working on the object they are dealing with
Having said that - Perhaps you should reexamine how you are using the class - because if you call this in your code
MyClass.Static.SomeProperty = "Something";
You are basically throwing away the object after it has been instantiated
you would need to assign it to a variable and store it. - the next time you call that function you will receive a new object.
Perhaps I was not able to explain properly, my question was referred multithreaded access on static properties.
I can confirm that they are thread-safe, if the returned object is bound to the current thread.
Here is the example of what I implemented:
public interface IObjectFactory
{
T CreateOrReuse<T>() where T : class, new();
T CreateOrReuse<T>(string key) where T : class, new();
T CreateOrReuse<T>(string key, params object[] args) where T : class;
}
public class ThreadObjectFactory : IObjectFactory
{
// implementation to create and store into the Thread Data
}
public class HttpSessionObjectFactory : IObjectFactory
{
// implementation to create and store into the current session
}
Now the singleton:
public class MyClass
{
public int PageLoadCounter = 0;
public static MyClass Static
{
get
{
IObjectFactory factory = new HttpSessionObjectFactory();
return factory.CreateOrReuse<MyClass>();
}
}
}
And this is the final use:
public class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyClass.Static.PageLoadCounter++;
}
}
Thanks for the replies, even if the question was not very clear

How are static constructors and private constructors different?

How are static constructors and private constructors different?
public class WorkstationDevicePresenter
{
private WorkstationDevicePresenter()
{}
}
What's the point in leaving them blank?
Whats the point in leaving them blank?
There are a number of reasons to make "blank" constructors.
You might make a blank constructor because you want a place to set a breakpoint during debugging.
You might make a blank static constructor because doing so changes the semantics of static field initializers. Read Jon's article on the subject for details.
Let's leave static constructors and consider blank instance constructors.
The key rule that motivates blank constructors is: By default if there are no constructors in a type then you get a "blank" parameterless public constructor for free. If there are any constructors in a type then you do not get a blank parameterless public constructor for free.
So the first obvious reason why you'd want a blank constructor is: I want a blank parameterless constructor, but I've already made another ctor, so I no longer get one for free.
The second reason is that you don't have any ctors and you do not want a blank parameterless public constructor. You might want a blank parameterless private, internal or protected constructor. If that's what you want then you'll have to make one yourself.
In particular, making an empty private ctor as the only ctor means that the class cannot be instantiated via a constructor from outside the class. This is very useful if you want to use the factory pattern. It also prevents code outside the class from making derived classes, because derived classes must be able to call a constructor. If all the constructors are private then they can't derive.
I frequently use this variation on the factory pattern:
public abstract class Thing
{
private Thing() {}
private class RedThing : Thing { ... }
public static Thing GetRedThing() { return new RedThing(); }
}
See, by making a private constructor I can make a public abstract class that can only be instantiated by my code and only extended by my code, and therefore I have a nice invariant: every time I see an object of type Thing, I know where it came from.
Static constructors happen once when the class is loaded, private constructors happen when they are called by some public static method typically used to create singletons, or with the Builder pattern. There is no reason to have a blank private constructor (that I know of).
Static constructors initialize the static parts of a class and private constructors can only be used by the class itself, like for creating a singleton-object of the class.
public class MyClass {
private static int staticitem;
private int instanceitem;
static MyClass(){
staticitem = 0; //define value for staticitem
}
private MyClass() { //can only be called from within the class
instanceitem = 0; //define value for instanceitem
}
public static MyClass GetMyClass() {
MyClass m = new MyClass();
return m;
}
}
Blank private constructor will make the class uninstantiable by anything other than itself. If you don't have this piece of code, by default the compiler creates a blank public parameterless contstructor.
Static constructor is called when creating the static instance.
You can use both to create a Singleton pattern, for instance.
Check the following code:
public class Singleton
{
public static Singleton Instance;
static Singleton
{
Instance = new Singleton();
}
private Singleton()
{
}
}
public class SomeOtherClass
{
public static Singleton CompileError = new Singleton();
public static Singleton CompileOK = Singleton.Instance;
}

How to return a static class instance in c#

I would like to get an instance of a static class, but I can’t seem to do this without implementing a singleton wrapper on a non-static class– is this possible, or am I missing something?
public class MyInstanceTester
{
public MyInstanceTester()
{
//this is how i get a reference to a singleton now
MyClass instance1 = MyClass.Instance();
//this is what is would like to do (if only the compiler would let me)
MyStaticClass instance2 = MyStaticClass.Instance();
}
}
public class MyClass
{
private static MyClass _myInstance;
static MyClass()
{
_myInstance = new MyClass();
}
public static MyClass Instance()
{
return _myInstance;
}
}
public static class MyStaticClass
{
public static MyStaticClass Instance
{
get
{
return this;
}
}
}
There is no such thing as an instance of a static class. The singleton pattern simply returns the same instance of a class to repeated requests.
You may be getting confused by:
private static MyClass _myInstance;
This simply means that there will be a single instance of that particular object among all objects instantiated of the type that have _myInstance as a member.
A few notes:
The this keyword is not valid in a static member
If you have a static class then all members have to be static and so this will never be valid
A Singleton class cannot be a static class
Singletons declare a single static member to help ensure that only a single instance of that class exists
Note that a static reference to an object does not make the object static. Only the reference is static
Further reading: Jon Skeet has an excellent write up on implemeting Singletons in C# In Depth. I would suggest reading and studying this article until you grok it. It is quite good.
There is no reason to return a instance to a static class ( If the class is static there is no instance ).
You can access the class from everywhere, why returning a instance to it? I can't imagine any reason to do this.
Static class usage
To use a static class just write it like below:
MyStaticClass.MyMethod();
Int32 callCount = MyStaticClass.CallCount;
As you can see it doesn't even make sense to declare a variable because this would just look like this:
MyStaticClass msc = MyStaticClass.Instance();
msc.MyMethod();
Int32 callCount = msc.CallCount;
If you want to have a shorter name you just can use:
using MSC = MyNamespace.MyStaticClass;
From your comments I assume your solution would be:
Make your class non-static. (Just keep the methods static.)
Your terminology is wrong. Please read the MSDN article on the static keyword.
A static member cannot be referenced through an instance. Instead, it
is referenced through the type name.
A singleton is a class that only allows a single instance of itself. A common implimentation of this in C# is:
public class MyClass
{
private MyClass _value = null;
public MyClass Value {
get { return _value ?? (_value = new MyClass()); }
}
}
The major problem is here:
public static class MyStaticClass
{
public static MyStaticClass Instance
{
get
{
return this; //compile time error!
}
}
}
this refers to an instance of a class which does not make sense in a static class as there can be no instance of one. This by itself should make you realize that there is a fundamental error in what you are asking: "I would like to get an instance of a static class". You can not return an instance of a static class as a static class by definition can not be instantiated.
The singleton pattern just makes sure that you always return the same instance of a class. But said class can never be static.

Categories

Resources