© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
5 replies
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Class with Func<> and class initializers
C#CC# / help
3y ago
List, Collection Initializer and Capacity
C#CC# / help
2y ago
❔ Error. Array initializer can only be used in a variable or field initializer.
C#CC# / help
4y ago
Module initializer only running for one assembly
C#CC# / help
5mo ago