Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# foreach against populated list is returning null

Following some major refactoring (moving to a PCL) I have some code (which was not part of the refactor) that was running fine but is now throwing exceptions.

The code is part of a Xamarin Android project which was using File Linking before the move to a Portable Class Library.

It's a simple thing but I can't see why this would happen

foreach(var station in stationList)
{

    // Breakpoint on next line shows station to be null..!
    if(station.ClusterId != Guid.Empty)
    {
        // Code in here
    }
}

The problem is that although the stationList contains a number of StationViewModel objects the station instance is always null - how can that be?

I have tried replacing the foreach with a for loop but the result was the same - station was null.

I've also restarted Visual Studio and rebooted.

No Xamarin updates appear to be outstanding.

The code was running fine and the generation of the stationList has not changed nor has the implementation of this class.

EDIT: The stationList creation process is:

  1. Call made to SQLite 'repo' in PCL which returns IList<station> (which is populated)

    _loadedStations = await _stationManager.GetStationsAsync();

  2. Using AutoMapper a new List<StationViewModel> is generated from the above list (which is populated correctly)

    fullStationList = AutoMapper.Mapper.Map<IList<Station>, IList<StationViewModel>>(_loadedStations);

  3. In a separate method the view model list above is filtered based on the LatLng coordinates.

    var stationList = fullStationList.Where(x => mapBounds.Contains(new LatLng(x.Latitude, x.Longitude))).ToList();

The foreach follows the above line of code..

SOLUTION: Well I've 'solved' the problem but still don't know what caused it.

In the same method as the foreach there is another, contained within an if. It too has the station identifier;

if (zoomChanged)
{
    foreach (var station in fullStationList)
    {
        station.ClusterId = Guid.Empty;
    }
    RunOnUiThread(() => _stationMap.Clear());
    _clusters.Clear();
}

By changing either of the variable names the code will run fine and the previously erroring loop will run without any problem.

Note that this 2nd loop was not within the 1st one - that's obviously not going to work, but I can't see why this was causing a problem.

like image 834
DilbertDave Avatar asked Oct 20 '22 01:10

DilbertDave


1 Answers

It seems like this has something to do with the way Xamarin works , changing var name solves the issue

 foreach(var stationItem in stationList)
 {

     // Breakpoint on next line shows station to be null..!
     if(stationItem.ClusterId != Guid.Empty)
     {
         // Code in here
     }
 }
like image 86
bilguunsparko Avatar answered Oct 22 '22 17:10

bilguunsparko