The problem might be the initialization order. A readonly
variable can only be assigned once (within the constructor when it's a class variable). When you create the object, the variable will already be initialized by the Student
constructor because this will be called first (before the constructor of CollegeStudent
). When you try to initialize it (again) in the CollegeStudent
constructor, it's already initialized and therefore an error raise.
Furthermore, I'd suggest some changes:
First: Make the properties not readonly
but define only a public getter and private/protected setter. This might already solve your problem.
public string Firstname {get; protected set;}
Second: The next thing is the constructor and the parameter names of your CollegeStundet
. As these are parameters (variables containing information) they look really strange. Better would be:
public CollegeStudent(string firstName, string lastName, string studentId)
You will use it like this to create a new CollegeStudent
object:
// this uses polymorphism as all CollegeStudnet are Student
Student studentX = new CollegeStundet("Tim", "Russel", "123AAA");
Third: Setting all the properties to the same value in the default constructor is really odd. In general, this will never be a good idea. Provide at least on general constructor to initialize all three to different values. You can still let them be "empty" (null - when using a default constructor) when you already followed my first suggestion.
Student(string firstName, string lastName, string studentId);
// the base keyword will pass the values to the constructor of Student
CollegeStudent(string firstName, string lastName, string studentId) : base(firstName, lastName, studentId)
But in general, I'd suggest to initialize them in the class where they are defined (Student
constructor in this case). When you need to change the values from outside Student
and you really want the values to be not writeable, there went something wrong with your concept.