This might be kind of Tricky. Basically I've got a class that looks like this:
class Timer
{
public string boss { get; set; }
public List<DateTime> spawnTimes { get; set; }
public TimeSpan Runtime { get; set; }
public BossPriority priority { get; set; }
}
As you can see, I want to add a list of DateTimes in my object. So I've created a list that looks like this:
List<Timer> bosses = new List<Timer>();
I was hoping that I could do something similar to this, to add the DateTimes:
bosses.Add(new Timer { boss = "Tequatl", priority = BossPriority.HardCore, spanTimes = { DateTime.ParseExact("07:00 +0000", "hh:mm zzz", CultureInfo.InvariantCulture) } });
Unfortunately, that is giving me a "Object reference not set to an instance of an object." error.
Doing it like this, doesn't make a difference either :(
Timer boss = new Timer();
DateTime t1 = DateTime.ParseExact("07:00 +0000", "hh:mm zzz", CultureInfo.InvariantCulture);
DateTime t2 = DateTime.ParseExact("11:30 +0000", "hh:mm zzz", CultureInfo.InvariantCulture);
boss.spawnTimes.AddRange(new List<DateTime> { t1, t2 });
Do I really have do .Add() on every DateTime?
Your NRE is caused by the fact you're not initializing Timer.spawnTimes
.
You can save on typing if you initialize the class as part of the default constructor:
public class Timer {
public List<DateTime> SpawnTimes { get; private set; }
...
public Timer() {
this.SpawnTimes = new List<DateTime>();
}
}
Another option is to have an overloaded constructor that accepts params
arguments:
public class Timer {
public List<DateTime> SpawnTimes { get; private set; }
...
public Timer() {
this.SpawnTimes = new List<DateTime>();
}
public Timer(String boss, /*String runtime,*/ BossPriority priority, params String[] spawnTimes) : this() {
this.Boss = boss;
// this.Runtime = TimeSpan.Parse( runtime );
this.Priority = priority;
foreach(String time in spawnTimes) {
this.SpawnTimes.Add( DateTime.ParseExact( time, "HH:mm" ) );
}
}
}
This is used in practice like so:
bosses.Add( new Timer("Tequat1", BossPriority.HardCore, "07:00 +0000" ) );
bosses.Add( new Timer("Tequat2", BossPriority.Nightmare, "01:00 +0000", "01:30 +0000" ) );
bosses.Add( new Timer("Tequat3", BossPriority.UltraViolence, "12:00 +0000" ) );
PascalCase
PascalCase
(unlike in Java where they're camelCase
)
public BossPriority priority
should be public BossPriority Priority
private set
instead of set
(implied public)Collection<T>
or ReadOnlyCollection<T>
instead of List<T>
or T[]
You're close... you just forgot to declare a new instance.
Add new[]
and then cast the the array to a List
:
bosses.Add(new Timer { boss = "Tequatl", priority = BossPriority.HardCore,
spawnTimes = new[] { DateTime.ParseExact("07:00 +0000", "hh:mm zzz", CultureInfo.InvariantCulture) }.ToList() });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With