C
C#2y ago
populus

List as a field of an object. [Answered]

public class Character
{
public string? Id { get; set; } // Identifier.
public List<string>? Name { get; set; } // In-game identifier.
}
public class Character
{
public string? Id { get; set; } // Identifier.
public List<string>? Name { get; set; } // In-game identifier.
}
static void Main(string[] args)
{
Character Populus = new Character();
Populus.Name[0] = "test";
}
static void Main(string[] args)
{
Character Populus = new Character();
Populus.Name[0] = "test";
}
What am I doing wrong? I'm trying to have a Character object with ever increasing amount of Names.
9 Replies
Aaron
Aaron2y ago
I'm assuming this throws a null reference exception? you aren't initializing Name to anything
populus
populus2y ago
System.NullReferenceException: 'Object reference not set to an instance of an object.' But does it make sense what I'm trying to do? How would you do it?
Aaron
Aaron2y ago
that happens because List<string> Name starts as null unless you add = new List<string>(); (also, you probably want Name.Add("test") instead of Name[0] = "test")
populus
populus2y ago
public Character()
{
this.Id = UtilityClass.createUUID();
this.Name = new List<string>();
}
public Character()
{
this.Id = UtilityClass.createUUID();
this.Name = new List<string>();
}
I added it in the constructor.
Aaron
Aaron2y ago
that works, although you can just do
public class Character
{
public string Id { get; set; } = UtilityClass.createUUID(); // Identifier.
public List<string> Name { get; set; } = new List<string>(); // In-game identifier.
}
public class Character
{
public string Id { get; set; } = UtilityClass.createUUID(); // Identifier.
public List<string> Name { get; set; } = new List<string>(); // In-game identifier.
}
populus
populus2y ago
Ah, I understand. Thanks @Windows10CE.
Accord
Accord2y ago
Ask the thread owner or member with permission to close this!
Aaron
Aaron2y ago
damn
Accord
Accord2y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server
More Posts