I have to create a Course Management System with course categories:
Cooking, sewing and writing courses
cooking
and writing
each have 2 courses (Italian, seafood, creative write and business write). This creates derived abstract:
abstract course -> abstract cooking -> concrete seafood
The abstract cooking and writing have common fields and some common methods, however they also have abstract methods that are abstract in the base class.
Can this be done in C#? If I make the derived abstract class methods abstract Visual Studio says they hide the base class abstract and then the concrete class methods have errors saying the base class must be abstract (it is but must not register). I have looked for an answer. I know single inheritance is used in C# but inheritance carries down the chain. What is the best answer?
Here is a code snippet - I hope it clarifies the problem:
public abstract class Course
{
public abstract void AddStudent(StudentName sn, int f);
public abstract decimal CalculateIncome();
}
public abstract class WritingCourse : Course
{
public void AddStudent(StudentName sn, int f)
{
//Add student
}
public abstract decimal CalculateIncome(); // can only be claculated in concrete
}
public class BusinessWritCourse : WritingCourse
{
public void AddStudent(StudentName sn, int f):
base(sn, false){}
public decimal CalculateIncome()
{
return //do stuff
}
}
public class SewingCourse : Course
{
public override void AddStudent(StudentName sn, int f)
{
//do stuff
}
public override decimal CalculateIncome()
{
return //do stuff
}
}
If I understand correctly I think you'd want to use the 'virtual' keyword on abstract methods you want to override?
If you are talking about the error that says something like "some method hides inherited member, add the new keyword if hiding was intended", then virtual on the base method and override on the inheriting method will do:
If you have base class 'A' which has an abstract method 'b()' then you don't have to declare 'b()' again as abstract in B : A, to have C : B override it, just don't use it. Even if you override the 'b()' method in class B you can again override it in class 'c()' (and even use base.(); to execute B's implementation.
Some code:
Also to clarify: methods declared abstract must be overriden (just like in an interface, and only by the direct child of the class declaring the abstract method). Methods declared virtual can be overriden, but don't have to be.
I think this kind of problems is better to resolve using interfaces and not abstract classes: Ex: