RE: Lazy Initialization in C#

You are viewing a single comment's thread from:

Lazy Initialization in C#

in programming •  7 years ago 

Great to see a C# post on steem!
I think this way is a good way to do it, I'm using similar code since C# 6 was out :)

About performance, depending on your class and how it's used, this might even improve performance because less garbage collection is needed.
e.g. If you initialize a list in a constructor, but only 50% of those classes will ever use it. then those empty lists will require collection later on without providing a benefit.

Also if performance is a huge point, code like this might still be useful in combination with ObjectPool, Span/Memory or an self-upgrading structure like the StringValues class (one shared empty instance, when upgrades into a single, then into a multi value object) instead of calling "new List<>".

However, it always depends on the usecase and project :)

I think especially for newer coders or in parts that are exposed to 3rd party code (e.g. a plugin system), this might be a great pattern to reduce unintended null reference exceptions and improve reliability.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!