Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access same object over two different interfaces

Tags:

c#

object

I have two interfaces :

interface IStudent
{
    string Name { get; }
    string EducationLevel { get; }
}

interface ITeacher
{
    string Name { get; }
    string Department { get; }
}

How would you design it in C# such that a an object could

  1. implement only Student (and don't have the teacher's properties)
  2. implement only Teacher(and don't have the strudent's properties)
  3. implement both of the interface without redundancy of the commone properties (Name)

Any thought ?

I can do 2 classes implementing directly the two interfaces. But for a person being both a teacher AND a student, I am going to have 2 different objects : I want only one !

like image 310
Toto Avatar asked May 17 '26 21:05

Toto


2 Answers

I would extract a common interface:

interface IPerson
{
    string Name { get; }
}

interface IStudent : IPerson
{
    string EducationLevel { get; }
}

interface ITeacher : IPerson
{
    string Department { get; }
}

Think about why your two interfaces have the same property. They both have a name, and why do they have a name? Because they're both a person. So there you have your common interface.

Classes implementing both interfaces will only need to implement Name once, because it's part of IPerson.

like image 58
Botz3000 Avatar answered May 19 '26 10:05

Botz3000


The following is perfectly legal:

public class LearningTeacher : ITeacher, IStudent
{
    public string EducationLevel
    {
        get { return /*...*/; }
    }

    public string Department
    {
        get { return /*...*/; }
    }

    public string Name
    {
        get { return /*...*/; }
    }
}

The Name property is the implementation of ITeacher.Name and IStudent.Name.

If the implementation of the properties is the same in Student and LearningTeacher you can make LearningTeacher have a Student instance and a Teacher instance internally, making it effectively a decorator. Like this, you wouldn't have to repeat the implementation:

public class LearningTeacher : ITeacher, IStudent
{
    Teacher _teacher;
    Student _student;

    public LearningTeacher(string name, string educationalLevel,
                           string department)
    {
        _student = new Student(name, educationalLevel);
        _teacher = new Teacher(name, department);
    }

    public string EducationLevel
    {
        get { return _student.EducationLevel; }
    }

    public string Department
    {
        get { return _teacher.Department; }
    }

    public string Name
    {
        get { return _student.Name; }
    }
}

This is the only way, because .NET doesn't support multiple inheritance. You can only implement multiple interfaces.

like image 38
Daniel Hilgarth Avatar answered May 19 '26 10:05

Daniel Hilgarth