C
C#2y ago
AdNecrias

❔ 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.
internal class Container {
internal string Label;
internal ICollection<Item> Items;
}
internal class Container {
internal string Label;
internal ICollection<Item> Items;
}
And had the method in an extension class:
internal static class Container {
internal static void AddItemToContainer(this Container container, Item item, string label = null)
{
if (container == null)
container = new Container() { Label = label, Items = new List<Item>() };
container.Items.Add(item);
}
}
internal static class Container {
internal static void AddItemToContainer(this Container container, Item item, string label = null)
{
if (container == null)
container = new Container() { Label = label, Items = new List<Item>() };
container.Items.Add(item);
}
}
Which i then wanted to use elsewhere as :
...

Container errors = null;

...

if(someCondition)
errors?.AddItemToContainer(new Item() { ... });

...
...

Container errors = null;

...

if(someCondition)
errors?.AddItemToContainer(new Item() { ... });

...
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
Anton
Anton2y ago
there is Lazy<T>
AdNecrias
AdNecriasOP2y ago
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.
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server