Lazy initialization in C#
Introduction
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
To learn more about lazy initialization, check this out
Why use it?
- When you have an object that has lots of data, but you only need some required data, the Lazy<T> class gives you access to load only specific data you need.
- It defers the creating of objects. It only initializes the object when needed
- It increases code performance
The code
The code here will be written in pure C#. Let's start with some basic console program.
Getting More Advanced
I created a generic class for a more advance lazy initialization. Since generic classes are type safe you can use it with any object as you wish. We are going to use the generic class to modify the console app. Let's start!
Viola!!! the results you would get is a collection of objects returned from Linq and you would notice i dumped the profile class and use another approach. You can tweak with the code as you wish, any type would work.
This class can also be used to work with complex json types and complex entities type. Yes!!! you can just pull out the data you need.
Comments
Post a Comment