How can I write a class in C# that only returns the "same" instance of an object? Is this effectively a singleton or different? This was mentioned in the book Effective Java 2nd addition.
I use C# 4.0 (no technology barrier).
How can I write a class in C# that only returns the "same" instance of an object? Is this effectively a singleton or different? This was mentioned in the book Effective Java 2nd addition.
I use C# 4.0 (no technology barrier).
Yes, this is a Singleton pattern. You'll find an excellent discussion based on our own Jon Skeet's C# implementation here.
If your Singleton object is expensive to create, but isn't used every time your application runs, consider using Lazy.
public sealed class LazySingleton
{
private readonly static Lazy<LazySingleton> instance =
new Lazy<LazySingleton>(() => new LazySingleton() );
private LazySingleton() { }
public static LazySingleton Instance
{
get { return instance.Value; }
}
}
using System;
namespace DesignPatterns
{
public sealed class Singleton
{
private static volatile Singleton instance = null;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
Interlocked.CompareExchange(ref instance, new Singleton(), null);
return instance;
}
}
}
}