Being lazy doesn't refer to being lazy in life, but being lazy about the creation or instantiation of objects in our code. Sometimes, creation of an object is very costly. Now, when we say "costly", we are not talking about money. Rather, we are talking about the memory consumed in the process and by the object itself.
Consider a component A that uses a service B. It is very likely for class A to have methods that do not use the object of class B. Please refer the code below,
Consider a component A that uses a service B. It is very likely for class A to have methods that do not use the object of class B. Please refer the code below,
- public class A
- {
- private B _b;
- public A(B b)
- {
- _b = b;
- }
- public void MethodOne()
- {
- _b.ClassBMethod();
- }
- public void MethodTwo()
- {
- // does not use _b
- }
- public void MethodThree()
- {
- // does not use _b
- }
- }
- public class B
- {
- public void ClassBMethod() { //do something }
- }
If we are using class A for MethodTwo and MethodThree only, we will overburden the runtime to instantiate B, which, in fact, will never be used. So, how do we handle it?
Using Lazy <T>
Using Lazy <T>

Join the conversation! Your thoughts help the community grow.