C
C#14mo ago
Emelie

❔ 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.
No description
No description
7 Replies
cap5lut
cap5lut14mo ago
there is a list initializer, so u can do it like this:
... = new()
{
new Player(...),
new Player(...)
};
... = new()
{
new Player(...),
new Player(...)
};
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.
Emelie
EmelieOP14mo ago
perfect, just what I was looking for! thank you
cap5lut
cap5lut14mo ago
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.
cap5lut
cap5lut14mo ago
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.
cap5lut
cap5lut14mo ago
if this answered ur questions please $close the thread
MODiX
MODiX14mo ago
Use the /close command to mark a forum thread as answered
Accord
Accord14mo 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