Search code examples
c#abstract-class

write constructor to initialize attributes csharp?


Hey Guys i could need some Help here. I'm supposed to implement an abstract class with some attributes (that I already have). Now I'm supposed to write a constructor that initializes the attributes and add getters and setters. Here I am stuck can someone tell me how to implement this?

Here is my abstract class

namespace Personalverwaltung { 

    public abstract class Person
    {
        public string Name;
        public string Adresse;
        public int Hausnummer;
        public int PLZ;
        public string Ort;   
    }
}

Solution

  • There are no Getters and Setters in C# (at least they are not advised as in i.e. Java implementations), there are only properties.

    Take a look here to help you: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties

    Example:

       private double _seconds;
    
       public double Hours
       {
           get { return _seconds / 3600; }
           set {
              if (value < 0 || value > 24)
                 throw new ArgumentOutOfRangeException(
                       $"{nameof(value)} must be between 0 and 24.");
    
              _seconds = value * 3600;
           }
       }
    

    For an example constructor, look here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors

    Both articles will help you learn when you implement them. There are enough examples and information to get you going. Good luck on your programming journey.