Lazy initialization in C#

Introduction


lazy initialization defers the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

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.



when you run the program, you will get "John Doe" as the result.


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

Popular posts from this blog

Paystack In Asp.Net MVC

Solved: Jwt Authentication in Asp.Net Web Api And Mvc

Coingate in .Net