❔ Null class auto initializer
I'm likely missing the obvious solution and am too tired to remember it but...
How do you go about making a class typed variable initialise itself when first being called?.
I want to have a Container<Item> that begins as a null and would remain so unless it receives an Item.
When it does, if it is null it should initialise itself and its internal List. After that it should add the item to the internal list.
I had the code inline but wanted to extract it to a common class as something like this would be used in several places.
And had the method in an extension class:
Which i then wanted to use elsewhere as :
But of course, calling it without the ? would result in a null reference exception.
Is there a way I can just have the null reference instantiate itself akin to this?
3 Replies
there is
Lazy<T>
Oh!
Thanks, that seems to be a way to do it.
I can't use the label with it, but that's an extra line that won't be used everytime so i don't mind having it as boilerplate.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.