Avoiding static variables with Singleton - c#

A colleague of mine told me that I should never use static variables because if you change them in one place, they are changed everywhere. He told me that instead of using static variables I should use Singleton.
I know that Singleton is for limitation of the number of instances of one class to one.
How can Singleton help me with static variables?

Let's address your statements one at a time:
A colleague of mine told me that I should never use static variables because if you change them in one place, they are changed everywhere.
It seems fairly clear that your colleague means the basic feature of static variables: there is only one instance of a static variable. No matter how many instances of any class you create, any access to a static variable is to the same variable. There is not a separate variable for each instance.
He told me that instead of using static variables I should use Singleton.
This is not good global advice. Static variables and singletons aren't in competition with each other and aren't really substitutes for each other. A singleton is an instance of a class, managed in such a way that only one instance is possible to create. A static variable is similarly tied to exactly one (static) instance of a class, but could be assigned with not only a class instance but any data type such as a scalar. In actuality, to effectively use the singleton pattern, you must store it in a static variable. There is no way to "use a singleton instead of a static variable".
On the other hand, perhaps he meant something slightly different: perhaps he was trying to say that instead of your static class having many different static variables, methods, properties, and fields (altogether, members) that function as if they were a class, you should make those fields non-static, and then expose the wrapping class as a Singleton instance. You would still need a private static field with a method or property (or perhaps just use a get-only property) to expose the singleton.
I know that Singleton is for limitation of the number of instances of one class to one. How can Singleton help me with static variables?
A static class's variables and a singleton are alike in that they both are instantiated once (the former enforced by the compiler and the latter enforced by your implementation). The reason you'd want to use a singleton instead of a static variable inside of a class is when your singleton needs to be a true instance of a class, and not consist simply of the collected static members of a static class. This singleton then gets assigned to a static variable so that all callers can acquire a copy of that same instance. As I said above, you can convert all the different static members of your static class to be instance members of your new non-static class which you will expose as a singleton.
I would also like to mention that the other answers given so far all have issues around thread safety. Below are some correct patterns for managing Singletons.
Below, you can see that an instance of the Singleton class, which has instance (or non-static) members, is created either by static initialization or within the static constructor, and is assigned to the variable _singleton.. We use this pattern to ensure that it is instantiated only once. Then, the static method Instance provides read-only access to the backing field variable, which contains our one, and only one, instance of Singleton.
public class Singleton {
// static members
private static readonly Singleton _singleton = new Singleton();
public static Singleton Instance => _singleton
// instance members
private Singleton() { } // private so no one else can accidentally create an instance
public string Gorp { get; set; }
}
or, the exact same thing but with an explicit static constructor:
public class Singleton {
// static members
private static readonly Singleton _singleton; // instead of here, you can...
static Singleton() {
_singleton = new Singleton(); // do it here
}
public static Singleton Instance => _singleton;
// instance members
private Singleton() { } // private so no one else can accidentally create an instance
public string Gorp { get; set; }
}
You could also use a property default without an explicit backing field (below) or in a static constructor can assign the get-only property (not shown).
public class Singleton {
// static members
public static Singleton Instance { get; } = new Singleton();
// instance members
private Singleton() { } // private so no one else can accidentally create an instance
public string Gorp { get; set; }
}
Since static constructors are guaranteed to run exactly once, whether implicit or explicit, then there are no thread safety issues. Note that any access to the Singleton class can trigger static initialization, even reflection-type access.
You can think of static members of a class as almost like a separate, though conjoined, class:
Instance (non-static) members function like a normal class. They don't live until you perform new Class() on them. Each time you do new, you get a new instance. Instance members have access to all static members, including private members (in the same class).
Static members are like members of a separate, special instance of the class that you cannot explicitly create using new. Inside this class, only static members can be accessed or set. There is an implicit or explicit static constructor which .Net runs at the time of first access (just like the class instance, only you don't explicitly create it, it's created when needed). Static members of a class can be accessed by any other class at any time, in or out of an instance, though respecting access modifiers such as internal or private.

EDIT #ErikE's response is the correct approach.
For thread safety, the field should be initialized thusly:
private static readonly Singleton instance = new Singleton();
One way to use a singleton (lifted from http://msdn.microsoft.com/en-us/library/ff650316.aspx)
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
/// non-static members
public string Foo { get; set; }
}
Then,
var foo = Singleton.Instance.Foo;
Singleton.Instance.Foo = "Potential thread collision here.";
Note that the instance member is a static field. You can't implement a singleton without using a static variable, and (I seem to recall - it's been awhile) this instance will be shared across all requests. Because of that, it's inherently not thread safe.
Instead, consider putting these values in a database or other persistent store that's more thread-friendly, and creating a class that interfaces with that portion of your database to provide transparent access.
public static class Foo
{
public static string Bar
{
get { /// retrieve Bar from the db }
set { /// update Bar in the db }
}
}

The whole point of the static modifier is to ensure that the object thus modified is the same wherever it is used as it requires no instantiation. The name originally came about as a static variable has a fixed location in memory and all items referring to it will reference the same memory location.
Now you may wish to use a static field within a class, in which case it exists before the class is instantiated (constructed). There may be instances where you would want this.
A singleton is a different beast. It is a class that is limited to a single instantiation by use of a private constructor and a static property. So in that regard you still can't avoid statics by using a singleton.

To answer the stated question:
It is incredibly stupid (but possible) to create a singleton without a static field.
To do it, you need to use someone else's static field, such as AppDomain.GetData or (in ASP.Net) HttpContext.Application.

Just to answer your question (I hope): Instead of using a static class containing static members like Class1 you can implement the Singleton pattern like in Class2 (please don't begin a discussion about lazy initialization at this point):
public static class Class1
{
public static void DoSomething ()
{
}
}
public static class Class2
{
private Class2() {
}
private Class2 instance;
public Class2 GetInstance(){
if (instance == null)
instance = new Class2();
return instance;
}
public void DoSomething ()
{
}
}
Instead of calling Class1.DoSomething() you can use Class2.GetInstance().DoSomething().
Edit: As you can see there's still a (private) static field inside Class2 holding it's instance.
Edit2 in answer to user966638's comment:
Do I understand you correct that you have code like this:
public class Foo {
private static Bar bar;
}
And your collegue suggests to replace it by this?
public class Foo {
private BarSingleton bar;
}
This could be the case if you want to have different Foo instances where each instance's bar attribute could be set to null for example. But I'm not sure if he meant this what exactly is the use case he is talking about.

Both singleton and static variables give you one instance of a class. Why you should prefer singleton over static is
With Singleton you can manage the lifetime of the instance yourself, they way you want
With Singleton, you have greater control over the initialization of the instance. This useful when initializing an instance of a class is complicated affair.
It's challenging to make static variables thread-safe, with singleton, that task becomes very easy
Hope this helps

Related

Do two instances of a singleton class have the same property value?

I am new to design patterns in C#. Can anyone please give me some instructions about the implementation of a Singleton class. I just implemented a tutorial but I am not able to understand use of singleton class with this "singleton means we can create only one instance of a class". Then why we don't access property which is written in the singleton class using two different instance of the class.
Please look at my code and give me instructions about the mistake I made.
static void Main(string[] args)
{
Singleton instance = Singleton.getInstance();
instance.Message = "Text Message";
Singleton instance1 = Singleton.getInstance();
Console.WriteLine(instance.Message);
Console.WriteLine(instance1.Message);
Console.ReadKey();
}
class Singleton
{
private static Singleton singleton=null;
private Singleton(){}
public static Singleton getInstance()
{
if (singleton!=null)
{
return singleton;
}
return new Singleton();
}
public string Message{get; set;}
}
Your singleton is incorrect.
More correct version:
class Singleton
{
private static Singleton singleton = null;
private Singleton(){}
public static Singleton getInstance()
{
if (singleton!=null)
{
return singleton;
}
return (singleton = new Singleton()); //here is
}
public string Message{get; set;}
}
And very good solution:
class Singleton
{
private static Lazy<Singleton> singleton = new Lazy<Singleton>(()=> new Singleton());
private Singleton() { }
public static Singleton getInstance()
{
return singleton.Value;
}
public string Message { get; set; }
}
It has no problems with thread-safity and lazy initialization.
By default, all public and protected members of the Lazy class are
thread safe and may be used concurrently from multiple threads. These
thread-safety guarantees may be removed optionally and per instance,
using parameters to the type's constructors.
Your Singleton implementation is incorrect.
A Singleton is designed to only allow none or a single instance at all times.
This is where you went wrong:
public static Singleton getInstance()
{
// "singleton" will always be null.
if (singleton != null)
{
return singleton;
}
// Always returns new instance rather than existing one.
return new Singleton();
}
To fix it you should write:
public static Singleton getInstance()
{
// Return the instance we might have stored earlier.
if (singleton != null)
return singleton;
// Now we store the only instance that will ever be created.
singleton = new Singleton();
return singleton;
}
Note that this is not thread safe if called multiple times in parallel.
As a resource I can recommend Jon Skeet's post:
http://csharpindepth.com/Articles/General/Singleton.aspx
He explaines six different solutions (including thread-safety and the Lazy(T)) to the Singleton Pattern and how to code them.
Does two instance of singleton class has a same property value?
The answer to your question is yes, they has the same property value.
Important thing is understand why, and the reason is the core of what a singleton is. So, why?:
Because you are confusing two references with two instance.
There are no two instances, there are always one none or one instance of the singleton class.
In your code, singleton variable and singleton1 variable are pointing both to the same object, the singleton, and the reason is because of the implementation of the method getInstance(), is simple to understand :
If method is called for the very first time, then it creates for unique time the singleton object with method new.
If method is called after a first time, it will return the singleton object created in the first call of method.
So, no matter how many variables of type Singleton you have, you will always have only one Singleton created with the new method, the instance, the singleton instance.

Private static property in c#

Do I need to mark public method as static if I want to initialize private variable only once or it is enough for making "singleton property" in the following code?
public IEqualityComparer<T> GetComparer<T>()
{
if (typeof (IUserShift).IsAssignableFrom(typeof (T)))
return UserShiftComparer.Value as IEqualityComparer<T>;
throw new ArgumentOutOfRangeException("There is no avaliable comparer for the type!", nameof(T));
}
private static readonly Lazy<UserShiftTrackingComparer> UserShiftComparer = new Lazy<UserShiftTrackingComparer>();
If you make your field static then only one copy will exist and in this case since you have it within Lazy, it will only be created when it is accessed. If it is never accessed, it will never be created.
Making your method static means it is not tied to an instance of the class but the class itself. All instance methods can access static methods and static fields and instance fields and instance methods. On the other hand, static methods can only access static fields and other static methods.
To answer your question, you DO NOT need to make the method static to initialize the UserShiftComparer only once.

C# should Singleton contain static methods?

I am having a lot of trouble choosing between using Singleton or Static for a class that contains state variables. I wanted the class object to instantiate and exist only as one.
I know both ways can store state variables. Static Class seems easy to deal with the variables as all methods will become static, which they can access the static variables without any further work.
However, this case is different for a Singleton. I have both kinds of methods; A kind that needs to access to the Singleton's Instance variable, and other that without any access to the Instance variable, which I can mark it static.
An Example:
/// <summary>Singleton.</summary>
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton(); /// <summary>Instance.</summary>
public static Singleton Instance { get { return instance; } }
private int integer; /// <summary>Integer.</summary>
public int Integer { set { integer = value; } get { return integer; } }
/// <summary>Constructor.</summary>
private Singleton() { }
/// <summary>TestA</summary>
public void TestA(int val)
{
Integer = val;
}
/// <summary>TestB</summary>
public static int TestB(int val)
{
return Instance.Integer * val;
}
/// <summary>TestC</summary>
public static int TestC(int val)
{
return val * val;
}
}
From the example given above, there are three methods; TestA, TestB, and TestC.
TestA is a non-static instance method that has access to its property.
TestB is a static method, but accesses the Instance to get its properties.
TestC is a static method that the instance has no use.
This begs the question:
Should the Singleton contains only static methods, and access to its Instance properties and methods by going through the static Instance property? In other words, all methods are similar to TestB or TestC.
Should the Singleton contains only non-static methods, regardless whether if it needs the Instance or not? All methods similar to TestA.
Should the Singleton contains both mixed static and non-static (in this case, TestA, and TestB kind) methods? Which I believe it can get rather messy.
If not, what should I do? Should I dump the idea of Singleton, and go with all static for every classes that is to be instantiated only once?
Edit: With similar question, should Singleton even contain any Static variables/field/properties beside the Instance?
You shouldnt mix up both patterns.
If you have an Singleton pattern the only static field should be the Instance(+ the getter). All your methods and fields should be accessible through the instance. If you mix it up it will only cause confusion.
If you choose the the static class pattern don't use a secret instance inside thats the job of .NET.
If you are not sure what pattern fits best for you, have a look into this Singleton-vs-Static article. It explains the pro's and con's of both of them: https://www.dotnetperls.com/singleton-static

Is this a valid Singleton in C# 6

I was making this to implement a singleton pattern
private static ProcessDao _dao;
public static ProcessDao Dao
{
get { return _dao ?? (_dao = new ProcessDao()); }
}
but in C# 6 auto properties has default values.
Is this a correct implementation of singleton?
public static ProcessDao Dao { get; } = new ProcessDao();
Is this a correct implementation of singleton?
Your first example is wrong in the sense that it isn't a thread-safe implementation of a singleton. If multiple threads called ProcessDao.Instance, you're likely to see different instances of the private field being created.
In contrary to that, your second example is thread-safe, as the compiler actually translates your auto-implemented getter only property to:
public class ProcessDao
{
[CompilerGenerated]
private static readonly ProcessDao <Dao>k__BackingField;
public static ProcessDao Dao
{
[CompilerGenerated]
get
{
return ProcessDao.<Dao>k__BackingField;
}
}
static ProcessDao()
{
ProcessDao.<Dao>k__BackingField = new ProcessDao();
}
}
The static constructor invocation is guaranteed by the runtime to at most once, so you're also getting the guarantee that this will not create multiple instances of the backing field.
Regarding laziness, that depends on the implementation of your ProcessDao class. The static constructor is guaranteed to run before the first reference of a static field in the class. If you have multiple static fields exposed, then the first will cause the invocation and the allocation of these objects. If you know you'll be using other static members and want maximum laziness, look into the Lazy<T> type introduced in .NET 4.0.

Why is 'readonly' essential in the following implementation of Singleton?

public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
I think even on removing readonly keyword from the instance member instantiation, the singleton would still work equally well.
Its static, only one instance would exist.
The value cant change, as it has no setter.
Its a sealed class, cant be subclassed.
Please help me correct my understanding of the concepts here.
Because if the field were not marked readonly it could be modified within the Singleton class. Of course, it still could not be modified by the outside world, but a singleton really isn't a singleton if there is more than one instance of it during the lifetime of your program, and the readonly specifier enforces the semantics that you want in a singleton class.
EDIT in response to:
Its static, only one instance would exist.
The value cant change, as it has no setter.
Static variables can certainly be set to reference different objects at runtime. The value can change, if only within the class due to it being private. If the class were implemented such that the field was only ever assigned to once, it wouldn't be a problem in practice. However, since the assumed intention is that the singleton instance will never change, the readonly modifier guarantees those semantics outside of the constructor. It's not essential because clients of the class cannot change the reference, but it is preferred because it a) makes the intent of the code clear, and b) prevents the reference from being changed even within the class.
Using readonly is not essential in this case but it is something that enforces the semantics of the code by indicating the nature of the field. Personally I always use the readonly keyword for all field declarations whose value is going to be initialized only once. It also might help the compiler perform some optimizations under certain circumstances.
I don't think readonly must present here - it makes sense only for lazy initialization. If you static field marked as readonly - it could be initialized only during declaration or in static constructor. If instance is not marked as readonly - you can initalize it during first call to Instance property.
BTW I think it's better to use singleton with double-check locking:
public sealed class Singleton
{
private Singleton()
{
// Initialize here
}
private static volatile Singleton _singletonInstance;
private static readonly Object syncRoot = new Object();
public static Singleton Instance
{
get
{
if(_singletonInstance == null)
{
lock(syncRoot))
{
if(_singletonInstance == null)
{
_singletonInstance = new Singleton();
}
}
}
return _singletonInstance;
}
}
}
I removed the readonly in a class because I wanted to make a OneAtaTimeleton (instead of a Singleton).
Why? Well, the class contained some configuration that I wanted the user (administrator) to be able to change while the app was running. So, I added a static Reload() method to the class, which has:
instance = new Configuration();
hence the need to remove the readonly.
The private version of the constructor loads the config (via a non-static method).

Categories