NullReferenceException was not controlled

-4

I am developing an application with C #, but it gives me the following error:

  

NullReferenceException was not monitored

     

Object reference not set as an instance of an object

as you can see in this image:

How can I solve this problem? This is the code of my project:

Rental Class

class Alquiler
{
    public DateTime fecha1;
    public DateTime fecha2;
    Vehiculos unv;
    Clientes uncl;

    public DateTime Fecha1
    {
        get { return fecha1; }
        set { fecha1 = value; }
    }
    public DateTime Fecha2
    {
        get { return fecha2; }
        set { fecha2 = value; }
    }

    public Alquiler(DateTime f1, DateTime f2, Vehiculos unve, Clientes uncli)
    {
        Fecha1 = f1;
        Fecha2 = f2;
        if (unve == null)
            throw new ArgumentNullException("unve es requerido");
            unv = unve;

        if (uncli == null)
            throw new ArgumentNullException("uncli es requerido");
            uncl = uncli;
    }

    public double CalcularAlquiler()
    {
        double costoTotalAlq = 0;
        costoTotalAlq = ((fecha2.Day - fecha1.Day) * unv.costodiario);
        return costoTotalAlq;
    }

    public virtual string MostrarAlquiler()
    {
        return "FECHA DE INICIO ALQUILER : " + fecha1 + " " + "FECHA FIN DE ALQUILER : " + fecha2; 
    }
}

Vehicle class:

class Vehiculos
{
    public string matricula, marca, modelo;
    public int año, cantidadpuertas;
    //public int digitos;
    public double costodiario;

    public string Matricula
    {
        get { return matricula; }
        set { matricula = value; }
    }
    public string Marca
    {
        get { return marca; }
        set { marca = value; }
    }
    public string Modelo
    {
        get { return modelo; }
        set { modelo = value; }
    }
    public int Año
    {
        get { return año; }
        set
        {
            if (value < 2017)
                año = value;
            else
                throw new Exception("No se trabaja con vehículos que aun no se construyeron");
        }
    }
    public int Cantidadpuertas
    {
        set
        {
            if (value < 2)
                throw new Exception("El vehículo tiene que tener mínimo 2 puertas");
            else
                cantidadpuertas = value;

        }
        get { return cantidadpuertas; }
    }
    //public int Digitos
    //{
    //    get { return digitos; }
    //    set { digitos = value; }
    //}
    public double Costodiario
    {
        get { return costodiario; }
        set
        {
            if (value < 25)
                throw new Exception("El costo diario mínimo es de 25 dólares");
            else
                costodiario = value;
        }
    }

    public Vehiculos(string mat, string mar, string mo, int a, int cant, double costo)
    {
        Matricula = mat;
        Marca = mar;
        Modelo = mo;
        Año = a;
        Cantidadpuertas = cant;
    //    Digitos = dig;
        Costodiario = costo;
    }

This is my Program:

 Console.WriteLine("---------------------------------------");
                    Console.WriteLine("            REALIZAR ALQUILER");
                    Console.WriteLine("---------------------------------------\n");
                    Console.Write("Ingrese cédula de indentidad : ");
                    cedula = Console.ReadLine();
                    Clientes n = emp.Buscar(cedula);
                    Console.Write("\n" + "Ingrese la mátricula del vehículo a alquilar");
                    Console.Write("\n" + "Mátricula : ");
                    matricula = Console.ReadLine();
                    Vehiculos k = emp.Buscarr(matricula);
                    if (n == null)
                    {
                        Console.WriteLine("\n"+ "El cliente no esta registrado");
                        if (k == null)
                        {
                            Console.WriteLine("\n" + "No existe el vehículo");
                        }
                    }
                    else
                    {
                        Console.Write("\n" + "Ingrese fecha de recogida del vehículo");
                        Console.Write("\n" + "Ingrese fecha inicio alquiler : ");
                        fecha1 = Convert.ToDateTime(Console.ReadLine());
                        Console.Write("\n" + "Ingrese la fecha de devolucioón del vehículo");
                        Console.Write("\n" + "Ingrese fecha fin alquiler : ");
                        fecha2 = Convert.ToDateTime(Console.ReadLine());
                        Alquiler alq = new Alquiler(fecha1, fecha2, k, n);
                        emp.Alquilar(alq);
                        Console.WriteLine("El costo total del alquiler es de : " + alq.CalcularAlquiler().ToString());
                        Console.WriteLine("\n" + "Se agrego correctamente el alquiler");
                    }
                    Console.ReadLine();
                    break;

And here I have the search for emp:

 public Vehiculos Buscarr(string mat)
    {
        Vehiculos v = null;
        for (int i = 0; i < lista.Count; i++)
        {
            if (lista[i] is Vehiculos)
            {
                if (((Vehiculos)lista[i]).Matricula == mat)
                {
                    v = (Vehiculos)lista[i];
                    i = lista.Count;
                }
            }
        }
        return v;
    }
    
asked by Francop 04.08.2017 в 16:05
source

3 answers

2

The Vehiculo object that you send in the constructor is passing as null and trying to access the property costodiario launches NullReferenceException . Make sure you are not passing null.

I recommend that when a class consists of several objects, it is best to verify that all objects are not null and thus ensure that all class methods and services have an object with value:

public Alquiler(DateTime d1, DateTime d2, Vehiculos unve, Clientes uncli)
{
  if(unve == null) throw new ArgumentNullException("unve es requerido");
  if(uncli == null) throw new ArgumentNullException("uncli es requerido");

  //...
}
    
answered by 04.08.2017 в 03:55
2

The problem is that k is null and only valid if n is null.

Vehiculos k = emp.Buscarr(matricula);

You have no errors in the code of your classes.

    
answered by 04.08.2017 в 16:22
1

There is no error in the code you published, therefore, the problem must be in the instance of the Rent object.

Be sure to instantiate it as follows:

DateTime f1 = DateTime.Now;
DateTime f2 = DateTime.Now.AddDays(5);
Vehiculos veh = new Vehiculos("mat", "mar", "mo", 5, 4, 15000);
Clientes cli = new Clientes();
Alquiler objeto = new Alquiler(f1, f2, veh, cli);
double resultado = objeto.CalcularAlquiler();

Clarify that there are many ways to write this code, this is just a proposal.

It is possible that you are passing a non-instantiated Vehicles object to it.

Greetings.

    
answered by 04.08.2017 в 16:20