Doubt in inheritance c#

Asked

Viewed 80 times

-2

I have a conceptual doubt about inheritance, where I have a student and at some point this student will become an employee and this employee he was born in the system as a student and if everything is ok during the process will become employee, then I have:

public class Aluno { public int Id {get;set;} public string Nome { get; set;} }

public class Empregado : Aluno { public decimal Salario { get; set;} }

So a student is created:

var aluno = new Aluno { Id = 1, Name = "Roberto" };

My question is how to make this student days later become an employee, keeping the same Id and Name?

  • 4

    You’re trying to model your classes based on a workflow (student > Employee), and perhaps not the best form (that, my humble opinion). Let’s think about it this way: has every employee necessarily been a student one day? I believe the answer is nay, So this modeling doesn’t seem ideal. Maybe you can model a class called "Person", and Student and Employee inherit from it, thus extending "Person", it seems to me to make more sense.

1 answer

1


There may be a problem with your way of thinking. The way your code is structured, an Employee is also a Student. The concept of inheritance does not mean going from one stage to another, but rather specialization.

Edit: I haven’t noticed any information about the employee, so I’m changing the answer.

Since you want to keep the name and ID information, it might be a good idea to abstract the logic of "evolution" to a separate abstract class, which will give you the opportunity to add specific information from each "position", for example:

A person class as a basis, to keep your registration data:

public class Pessoa
{
    public int Id {get;set;}
    public string Nome {get;set;}

    public virtual Cargo Cargo {get;set;}
}

Office is an abstract class, and you will have two classes defining different behaviors that you will inherit from it.

public abstract class Cargo
{
    public int Id {get;set;}
    public string Nome {get;set;}
}

public class CargoEstudante : Cargo
{
    public bool Concluido {get;set;}
}

public class CargoEmpregado : Cargo
{
    public decimal Salario {get;set;}
}

Therefore, you could specify extension methods to make your life easier and find out if a Person is a student or works (or both if it makes sense in your application).

public static class ExtensoesPessoa
{
    public static bool IsEstudante(this Pessoa p)
    {
        return p.Cargo is CargoEstudante;
    }

    public static bool IsEmpregado(this Pessoa p)
    {
        return p.Cargo is CargoEmpregado;
    }
}
  • Good danspark day, your solution does not encompass the specific characteristics of an employee (salary).

  • @Good morning, I edited the answer according to what you said, I think now is solving the problem correctly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.