System.Lazy in C#

System.Lazy in C#

During a work task, I was asked to manage the loading of an object just once in its first usage.

It is something that I have had several times throughout my career. But I always did the same way, manually with an “if null” verification.

However, there is a class that has existed in .NET since version 4.0, in 2010, called Lazy.

The funny thing is that until a few days ago, I never considered this possibility until I realized it during web research.

Here is an example of the normal handling:

And here, the same code, using Lazy:

Another advantage is that it has the safe-thread option embedded, just passing true as a second parameter:

And it is also a great option to work with the Singleton pattern:

João Vinícius Fernandes

Senior Software Engineer | Java | Spring Boot | AWS | React | Angular | JavaScript | TypeScript

6mo

Love this

Kaique Perez

Fullstack Software Engineer | Frontend-Focused | Typescript | React | Next.js | Tailwind | AWS | NestJS | TDD | Docker | Nodejs

6mo

Well said and thanks for sharing! Cassio Almeron

Gabriel Levindo

Android Developer | Mobile Software Engineer | Kotlin | Jetpack Compose | XML

6mo

Well done!!

Julio César

Senior Software Engineer | Java | Spring Boot | AWS | React | Angular | LLM | GenAI | CI/CD | MySQL | MongoDB | JUnit | Mockito | APIs

6mo

Excellent.

Otávio Prado

Senior Business Analyst | Agile & Waterfall | Data Analysis & Visualization | BPM | Requirements | ITIL | Jira | Communication | Problem Solving

6mo

Nice solution! Thanks for sharing Cassio Almeron ! 🚀💯

To view or add a comment, sign in

Others also viewed

Explore topics