0

im having a System.NullReferenceException and dont know why, and dont find the solution, i searchig for a solution around 3 hours, and nothing, someone can helpme , please, ill apreciated it here is my class, and my method with the trouble

public class FuenteDatos 
{
    private Contexto db = new Contexto();

    public List<string> Area { get; set; }

    public List<int> Cantidad { get; set; }

    public FuenteDatos ObjetenerDatosDescripcion(string parametro) 
    {
        FuenteDatos obj = new FuenteDatos();

        var porAreas = from receptores in db.AFTs
        where receptores.Descripcion == parametro
        group receptores by receptores.Receptor.AreaTrabajo into tablanueva
        select new {
            a = tablanueva.Key,
            c = tablanueva.Count(),
        };

        //debugin i have all the rights values, till this point everything is ok

        foreach(var objeto in porAreas) 
        {

            //here is the exeption system null reference , WHYY? the anonymous field "a" is not empty 
            //or null
            obj.Area.Add(objeto.a);
            obj.Cantidad.Add(objeto.c);

        }

        return obj;
    }

}
Sotiris Panopoulos
  • 1,523
  • 1
  • 13
  • 18
  • which line are you getting exception? – Vivek Nuna Jun 10 '20 at 06:19
  • 1
    Did you check whether `obj.Area` or `obj.Cantidad` is null? – C.Evenhuis Jun 10 '20 at 06:25
  • 1
    `obj = new FuenteDatos()` only creates an instance of the class. It does not magically set its properties to anything meaningful - except null. You pretty sure need something like `obj.Area = new List()`. – MakePeaceGreatAgain Jun 10 '20 at 06:32
  • @viveknuna im getting the exception in the line >>obj.Area.Add(objeto.a);< – HOLDTHEDOOR Jun 10 '20 at 14:11
  • @HimBromBeere , i know when i create a instance of a class, the obj in this case is null, but have the poperties of the class, so , in trying to add the fields of the anonymous type to each field of the instance of the class FuenteDatos, the logic is fill the lists with the data of the annonimous type – HOLDTHEDOOR Jun 10 '20 at 14:14
  • @HimBromBeere this works obj.Area = new List();, but i dont understand why, i belive that when the List Area is defined in the class all the job is done, i just have to create and instance of the class and fill the string list. with add(). thanks a lot for the answer, super usefull, im keep studying c# and english ;) – HOLDTHEDOOR Jun 10 '20 at 14:26

0 Answers0