AdNecrias
AdNecrias
CC#
Created by AdNecrias on 1/17/2023 in #help
❔ 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?
6 replies