TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Creating Lazy<T> - Singleton Class
Mahadesh Mahalingappa
Sep 27, 2011
11.8
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
In this blog we will see how to create a Singleton Class using the Lazy
in C#.
Lazy<T> provides support for
Lazy Initialization
.
By Lazy Intialisation we mean that an object is not intialised until it is actually used. Below, I have shown how we can combine the Lazy<T> with the Singleton Pattern.
public sealed class LazySingleton
{
// Private object with lazy instantiation
private static readonly Lazy<LazySingleton> instance =
new Lazy<LazySingleton>(
delegate
{
return new LazySingleton();
}
//thread safety first
, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
private LazySingleton()
{
// no public default constructor
}
// static instance property
public static LazySingleton Instance
{
get { return instance.Value; }
}
}
Related Resources
Here is a list of some other related resources:
System.Lazy(Of T) Class
Lazy Initailization in .NET 4.0
Support for
Lazy Initialization
in .Net 4.0
Next Recommended Reading
Create Object to Generic or Unknown Class