How to make a Class property of another Class? C#

Asked

Viewed 245 times

1

I am doing a job of the facul that is for control of fleet of vehicles, I created a class Travel and I tried to put the classes Driver and Vehicle in this class.

public Motorista {get; set;}
public Veiculo {get; set;}

Created a registration screen for travel and in the command Insert I did so:

Viagens viagens = new Viagens();
viagens.Motorista.CPF = txtCPF.Text;
viagens.Veiculo.Placa = txtPlaca.Text;
bll.InsertViagem(viagens);

But when doing Insert I get an error "Object reference not defined for an object instance"

What do I have to do to make this mistake? Because my Travel class needs the CPF of the Driver class and the Vehicle License Plate class, I thought that this way employee, but not... I’ll be very grateful if someone helps.

  • Understood the solution?

2 answers

1

Missing property name or type:

public Motorista {get; set;}
public Veiculo {get; set;}

Seria:

public Motorista Motorista {get; set;}
public Veiculo Veiculo {get; set;}

You also need to instantiate the Driver and Vehicle class:

Motorista motorista = new Motorista();
motorista.CPF = txtCPF.Text;

Veiculo veiculo = new Veiculo();
veiculo.Placa = txtPlaca.Text;

Viagens viagens = new Viagens
{
    Motorista = motorista,
    Veiculo = veiculo 
};

bll.InsertViagem(viagens);

0

To access a class member you need to first create your instance, and the message itself says: Undefined object reference to an object instance, but, as it would be in practice:

Classes

public class Motorista
{

}
public class Veiculo
{

}

In the member itself:

public class Viagens
{
    public Motorista Motorista { get; set; } = new Motorista(); // instância
    public Veiculo Veiculo { get; set; } = new Veiculo(); // instância
}

or

In the construtor class:

public class Viagens
{
    public Viagens()
    {              
        Motorista = new Motorista(); // instância
        Veiculo = new Veiculo(); // instância
    }
    public Motorista Motorista { get; set; }
    public Veiculo Veiculo { get; set; }
}

or even

After the main instance, instantiate its complex members:

Viagens v = new Viagens();
v.Motorista = new Motorista();
v.Veiculo = new Veiculo();

I believe these are the most traditional and can help you understand, that a complex data needs to be instantiated so you can access your programming.

Browser other questions tagged

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