Home > front end >  C# variable in a function become randomly not available
C# variable in a function become randomly not available

Time:06-01

I'm not really sure if I will be able to explain this behavior but I'll try. I have a program like a dashboard where some graph modules are initialized at startup, each module has a sole purpose to show a graph has a function passed to it which determine the data shown. The module building (initializing each module type with the corresponding function) is handled in a separate thread using Task. But randomly some of these functions stop working and the List with the data stop being available as if it was never declared.

This is one of the functions, keep in mind it's kind of random which one throws this error, but one of these will always throw an exception. I really can't track down what could cause this behavior I thought about the resources being deleted by other thread but this List is created at startup and only passed and used as a reference. And nowhere in the program I ever reset this list. The same code work in other project and while debugging step by step... I'm really out of tracks to follow

  private static IEnumerable<ICompositeValue> GroupEvent(IEnumerable<Event> events, DateTime referenceDate, Month month)
        {

            List<ICompositeValue> Values= new List<ICompositeValue>();
    
            foreach (Days day in (Giorni[])Enum.GetValues(typeof(Days)))
            {
                if (day != Giorni.Sunday)
                    if (events== null) return null; //this was tried to catch the exception
                    Values.Add(new ICompositeValue()
                    {
                        Argument = day.ToString(),
                        Valore = event.Count(x => (int)x.DDB_APDATA.Value.DayOfWeek == (int)day && (int)x.DDB_APDATA.Value.Month == (int)month && x.DDB_APDATA.Value.Year == referenceDate.Year)

                    }); ;
            }


            return valori;
        }

As shown in this image Visual Studio can't even evaluate the List value as if it was never declared

Can someone point me in the right direction?

Thanks to everyone!

I just wanted to thank those who tried to help me.

I still didn't get why the debugger acted the way it did since it showed me "x" was null not the inside property, but I managed to track down the problem. I noticed the object mapping from the DataTable was acting strange with the DateTime type variable and indeed something returned null from time to time

CodePudding user response:

As Jeroen Mostert has suggested it seems like some property in your lambda is unexpectedly null. The reason events is not available is because your debugger context is inside the lambda.

x => (int)x.DDB_APDATA.Value.DayOfWeek == (int)day && (int)x.DDB_APDATA.Value.Month == (int)month && x.DDB_APDATA.Value.Year == referenceDate.Year

So one of either x, DDB_APDATA, or Value will likely be null.

  • Related