Link Search Menu Expand Document

Fundamentals of Lazy Initialization in C# - Part-3


In this video, we’ll be going to explore lazy initialization in more detail. We’ll learn how the Lazy class can cache exceptions that are thrown from the initialization. What happens if we subsequently call them. We’ll learn how we can enable exception caching.

With the lazy class, you can cache exceptions that are thrown from the initialization. When we use this basic version of the lazy constructor, exception caching is not enabled. In the demo code in this class, we have a different constructor. As you can see here, when we initialize this (public class PatientDetail) object, this [Console.WriteLine(“– Constructor is called–”)] constructor will first log this message on the console. Then throws this exception with a message (exception generated time). Now, one thing to notice here is that we have logged the exact date and time when the exception is thrown.

Lazy Initialization C#

When we run this application first, it will create an object of the lazy class. Then we access this value property [(lazyPatientDetail.Value.PerformSomeOperation();]. But this method will never be called. As in the constructor, we throw this exception, and then we will get that exception over here [Console.WriteLine(ex.InnerException.Message)]. We are doing the same thing again.

Now let’s run this code. The exception is thrown. For the second call, we get the same exception. As you can see here, the first exception was created at 1:52:55 AM. We got the second exception at 1:53:09 AM. One thing to note here is that our constructor is called twice and we got the two distinct exception messages. Now you can cache this exception when we use an overloaded constructor of a lazy class. What this means is if the first time we access the value property, the constructor throws an exception and this exception will be cached by this lazy class. Any subsequent access to this value property will return the same cache exception. This also means that the constructor won’t be called a second time. So let’s see this in action. When I hit enter, we get an exception message.

Lazy Initialization C Sharp

In the output, you can see that we got our first exception at 1:57:51 AM. On the second attempt, we got the same exception message at the same time. Notice here that our constructor is called only one time. That’s because we are using the overloads of the lazy constructor. When we do this exception, caching is automatically enabled for us.

For more videos and articles visit:

👉 GET YOUR FREE API KEY for PDF.co

https://app.pdf.co/signup?utm_source=youtube

✅ ON-PREMISE SDK FREE TRIAL:

https://bytescout.com/download/web-installer?utm_source=youtube

🔎 SDK DOCUMENTATION:

https://bytescout.com/documentation/

🔑 WEB API DOCUMENTATION :

https://pdf.co/rest-web-api