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:
Senior Software Engineer | Java | Spring Boot | AWS | React | Angular | JavaScript | TypeScript
6moLove this
Fullstack Software Engineer | Frontend-Focused | Typescript | React | Next.js | Tailwind | AWS | NestJS | TDD | Docker | Nodejs
6moWell said and thanks for sharing! Cassio Almeron
Android Developer | Mobile Software Engineer | Kotlin | Jetpack Compose | XML
6moWell done!!
Senior Software Engineer | Java | Spring Boot | AWS | React | Angular | LLM | GenAI | CI/CD | MySQL | MongoDB | JUnit | Mockito | APIs
6moExcellent.
Senior Business Analyst | Agile & Waterfall | Data Analysis & Visualization | BPM | Requirements | ITIL | Jira | Communication | Problem Solving
6moNice solution! Thanks for sharing Cassio Almeron ! 🚀💯