-2

I know that most cases of a NullReferenceException are caused of missing initialization. But I initializated MTemp and FTemp.

What I'm missing?


Important code inside the class "Foo":

class Team
{
    public List<Fahrer> TeamFahrer { get; set; }

    public void Bar(string salad, string hotdog, string brokkoli)
    {
        Motorrad MTemp = new Motorrad(brokkoli);
        Fahrer FTemp = new Fahrer(salad, hotdog, MTemp);
        TeamFahrer.Add(FTemp);
    }
}

Important code inside Motorrad:

class Motorrad
{
    public Motorrad(string marke)
    {
        Marke = marke;
    }

    public string Marke { get; set; }
}

Important Code inside Fahrer:

class Fahrer
{
    public Fahrer(string salad, string hotdog, Motorrad moped)
    {
        Vorname = salad;
        Nachname = hotdog;
        MotorradDesFahrers = moped;
    }

    public string Vorname { get; set; }
    public string Nachname { get; set; }
    public Motorrad MotorradDesFahrers { get; set; }
}
Alex Held
  • 123
  • 9
  • 1
    Do you initialize `TeamFahrer`? – Grace Jul 15 '16 at 17:04
  • You haven't initialized TeamFahrer. Before you call "Add", you need to call TeamFahrer = new List(); – Jon Jul 15 '16 at 17:04
  • 1
    You are missing information about exception AND what of steps you've taken to debug after reading the "How to fix NRE" question already proposed as duplicate. (I think this is just poorly researched question - so not voting to close yet and just downvoting) – Alexei Levenkov Jul 15 '16 at 17:06
  • Thanks! I searched the whole time at the wrong end! – Alex Held Jul 15 '16 at 17:06

1 Answers1

0
class Team
{
   public List<Fahrer> TeamFahrer { get; set; }
   public Team()
   { 
     TeamFahrer  = new List<Fahrer>();
   }
}

Initialize TeamFahrer in the constructor of your class.

Saket Choubey
  • 848
  • 6
  • 11