Question by
GaryOPostle · Oct 08, 2015 at 08:51 PM ·
c#listarraysstring
How Do I Create a List of Two Strings? C#
I want to create a list of people who die with their name and occupation and then create a gravestone for them.
public TownDeaths[] ListOfDead;
public class TownDeaths{
public string deadName;
public string deadJob;
public TownDeaths(string name,string job){
deadName = name;
deadJob = job;
}
This is the code I use but I keep getting errors saying "Object reference not set to an instance of an object" whenever I try to create the tombstones. I would also like to know how to add to the list. Possibly even another string or int? Please and Thankyou!!
Comment
Best Answer
Answer by Dave-Carlile · Oct 08, 2015 at 08:59 PM
Arrays must be allocated before you can use them...
const int MaxDeaths = 20;
public TownDeaths[] ListOfDead = new TownDeaths[MaxDeaths];
If you will have a variable number of deaths then I would suggest using a collection instead of an arrary...
using System.Collections.Generic;
...
public List<TownDeaths> ListOfDead = new List<TownDeaths>();
...
// then you can add to the list like this...
ListOfDead.Add(new TownDeaths("Dead Guy", "Undertaker"));