0

The code is in German but it's not complicated. I'm creating an employee array, and in the end I have to sum all the monthly salaries ("lohnkosten" in german).

The problem I get is the NullReferenceException because I'm trying to have a [10] array and I have initialized only [6] members/employees in it. This is on purpose 'cause I want to have empty "slots" to write a method of adding and removing the members of this array. Now, when it tries to add all the salaries of all the members it comes to a null (empty) "slot" and therefore throws the NullReferenceException.

Is there a way to say to the program something like "if the null spot comes up, ignore it/skip it and do the rest." And I have to say in advance, I can't use List; it would be easier, but unfortunately I can't.

mitarbeiter.Berechnung() is the method for getting an employee's salary based on the hours which are the fourth parameter in the constructor.

Mitarbeiter[] alleMit = new Mitarbeiter[10];
alleMit[0] = new Arbeiter("001689", "Jimmy Page", "Lange Gasse 6, 1060 Wien", 2005, 10.75, 325.90);
alleMit[1] = new Arbeiter("001055", "Michael Jäger", "Lerchenfelderstraße, 1070 Wien", 1998, 12.50, 489.60);
alleMit[2] = new Angestellter("03569", "Toni Montana", "Margaretenstrasse 68, 1040 Wien", 2008, 11.85);
alleMit[3] = new Angestellter("03521", "Ray Charles", "Friedensbrücke 2, 1180 Wien", 2000, 12.65);
alleMit[4] = new Manager("00112", "Sarah Schwack", "Wiedner Haupstrasse 25, 1040 Wien", 2009, 14.75, 624.14);
alleMit[5] = new CEO("001", "Robert Plant", "Am hof 7, 1010 Wien", 1997, 22.50, 1445.80);

double lohnKosten = 0;
foreach (Mitarbeiter mitarbeiter in alleMit)
{
    mitarbeiter.Drucken();
    lohnKosten += mitarbeiter.Berechnung();
}
Console.WriteLine("\nLOHNKOSTEN: " + lohnKosten + " euro");

2 Answers 2

3

You could use LinQ to remove null entries before looping them. Like this

foreach(Mitarbeiter mitarbeiter in alleMit.Where(x => x != null))
{
    mitarbeiter.Drucken();
    lohnKosten += mitarbeiter.Berechnung();
}
Sign up to request clarification or add additional context in comments.

Comments

2

Just use an if statement and check for null:

foreach(Mitarbeiter mitarbeiter in alleMit)
{
    if(mitarbeiter != null)
    {
       mitarbeiter.Drucken();
       lohnKosten += mitarbeiter.Berechnung();
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.