❔ How do I initialize a static list with objects? (Quidditch app)
I am feeling completely lost on this. I have a playermanager which contains a static list of Player objects.
but no matter what I do, I get errors when I try to add demo players to the list... Why is this? I have attached an image of the static list and the player class itself.
7 Replies
there is a list initializer, so u can do it like this:
there r a lot helpful initializers u might want to read through: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers
Object and Collection Initializers - C# Programming Guide - C#
Object initializers in C# assign values to accessible fields or properties of an object at creation after invoking a constructor.
perfect, just what I was looking for! thank you
and if u would have more complex logic going on, u would use static constructors
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
Static Constructors - C# Programming Guide - C#
A static constructor in C# initializes static data or performs an action done only once. It runs before the first instance is created or static members are referenced.
the shown way is just syntax sugar, under the hood a static constructor is generated for that anyway.
u can observe this here: https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQAwAIpwCwG5nJQDMmM6AwsgN7Lp3oAOATgJYBuAhgC4CmmcANnQAZFgGcuAHhYA7LgD50MgK4BbAEY8mY9AF4lPAO4AKAJToq6OABp0ZAL74k9oA==
SharpLab
C#/VB/F# compiler playground.
if this answered ur questions please $close the thread
Use the /close command to mark a forum thread as answered
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.