Lazy type
- C# 4.0 introduced Lazy type, for lazy loading.
Lazy loading
Lazy loading refers to creating and initializing of objects only when it is required for the first time. That means,
you can define the object whenever you wish to, but it actually gets created only when you access its method/property/function.
Benefits of Lazy loading
- Improves the startup time of a C# application.
- Better performance and memory optimization.
Code For implementation:
Example
With Default or non-parametrize constructor.
- class Clent
- {
- int[] l_objNumberOfDoc ;
-
-
- public Client()
- {
- Console.WriteLine("Create instance of Client");
- l_objNumberOfDoc = new int[10];
- }
- public int NumberOfDoc
- { get { return l_objNumberOfDoc.Length;} }
- }
-
-
-
- class Program
- {
- static void Main()
- {
-
- Lazy<Client> lazy = new Lazy<Client>();
-
-
-
- Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated);
-
-
-
- Client l_objClient = lazy.Value;
-
-
- Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated);
-
-
- Console.WriteLine("Length = {0}", l_objClient.NumberOfDoc);
- }
- }