Search code examples
c#c#-4.0inheritancemultiple-inheritance

C# Multiple Inheritance


Currently im studying the C# with ASP.NET MVC 4 with Code First Approach. Im Visual Basic Developer, and Now i want to Start C#. And, now i came accross the situation where i've to manage Multiple Inheritance. But, it is not possible with Class i thought. So, how should i manage these classes i have :

//I have the Following Person Class which Hold Common Properties 
//and a Type of Person e.g : Student, Faculty, Administrative
public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Type { get; set; }
}


//This is my Student Class, which is Derived from Person
public class Student : Person
{
    public DateTime DateOfBirth { get; set; }
    public DateTime EnrollmentDate { get; set; }
    public string Remarks { get; set; }

    public bool Approved { get; set; }
    public DateTime ApprovedDate { get; set; }
    public int ApprovedUserId { get; set; }
}


//This is my Faculty Class, which is also Derived from Person
public class Faculty : Person
{
    public DateTime HiredDate { get; set; }

    public bool Approved { get; set; }
    public DateTime ApprovedDate { get; set; }
    public int ApprovedUserId { get; set; }
}

What I want to Make is Approved, ApprovedDate, and ApprovedUserId also common. I want to Specify those Properties like :

 public class Approve {
    public bool Approved { get; set; }
    public DateTime ApprovedDate { get; set; }
    public int ApprovedUserId { get; set; }
}

And, want to use like :

public class Student : Person, Approve
{
    public DateTime DateOfBirth { get; set; }
    public DateTime EnrollmentDate { get; set; }
    public string Remarks { get; set; }
}

And, i cannot put those things inside PERSON. Because, i've to use this to another classes to, but those are not Person.

Then, how do i achieve this...

Please give me an Example for the Above Situation.

Please Help. And, Thank You so much in Advance.


Solution

  • One possible solution would be to modify your hierarchy:

    public class PersonWithApprove : Person { // TODO: replace with non disgusting name
        public bool Approved { get; set; }
        // etc...
    }
    
    public class Student : PersonWithApprove {
    }
    
    public class Faculty : PersonWithApprove {
    }
    

    Or you could create an interface:

    public interface IApprove {
        bool Approved { get; set; }
        // etc
    }
    
    public class Student : Person, IApprove {
    }
    

    You might also leave the class Approve as such, and have classes with a property of that type:

    public class Student : Person {
        Approve _approve = new Approve();
        public Approve Approve {
            get { return _approve; }
        }
    }