Doubt in inheritance c # [duplicate]

-2

I have a conceptual question 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 an 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;} }

Then a student is created:

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

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

    
asked by anonymous 27.07.2018 / 12:50

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 did not notice any information about the employee, so I'm changing the answer.

Since you want to keep the name and ID information, it may be a good idea to abstract the "evolution" logic to a separate abstract class, which will give you the opportunity to add specific information for each "post", 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;}
}

Cargo is an abstract class, and you will have two classes defining different behaviors that 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;}
}

So you could specify extension methods to make your life easier and find out if a Person is a student or works (or both 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;
    }
}
    
27.07.2018 / 14:58