Bearowl
Bearowl

Reputation: 87

How do you create an Array for every Object and add it to a List (c#)

What I'm trying to do is create multiple Objects of the same class, each with their own set of values (e.g. a name, an address and a personal number) saved in an array, and later add it to a list of employees but when I try to create an Object the name and address stay as null. This is what I have so far:

 abstract class Person
{
    static public string _name;
    static public string _adresse; 

}

class Student : Person
{
    #region fields

    public string _personalnumber = Fakultät.generate_personalnr();

    #endregion

    //initiating the array witht the Infos about the Student
    public string[] StudentenA = new string[3] { Person._name, Person._address, personalnumber };

    #region const
    public Studenten (string name, string address)
    {
        Person._name = name;
        Person._address = address;

    }
    #endregion

Thanks in advance for your help. Bearowl

edit 1: changed the variables to all English (all German in original Project)

Upvotes: 1

Views: 216

Answers (2)

The Lyrist
The Lyrist

Reputation: 444

Since it looks like a homework, I am not writing out the exact code but try to help you with some hints.

The Person class is probably not written properly.

  1. If you want each person to have its own name and address, the fields shouldn't be static.

The Student class is probably not written properly.

  1. The person object already contains the name and address field. The student object inherits from it so you just need to add the personal number as another attribute. (i.e., you probably don't need the array within the Student class)
  2. You will need to update your constructor once you have fixed the parent class
  3. Once you finish properly coding the Person and Student class, you should then be able to create an array of 3 Student object in your main code

Edit: I have a proof of concept (tio.run) fix with examples for class inheritance (method override, etc.). Please let me know if I should share it here. Thanks!

Upvotes: 4

Erik Levin
Erik Levin

Reputation: 47

You should assign StudentenA in the constructor, so that it takes place after setting the _name and _address.

public Studenten (string name, string address)
{
    Person._name = name;
    Person._address = address;
    StudentenA = new string[3] { Person._name, Person._address, personalnumber };
}

But also, _name and _address of Person shouldn't be static. With static, only one instance of them exists - not all persons have the same name and address, do they? :)

Upvotes: 1

Related Questions