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:
Call made to SQLite 'repo' in PCL which returns IList
(which is populated)<station>
_loadedStations = await _stationManager.GetStationsAsync();
Using AutoMapper a new List
is generated from the above list (which is populated correctly)<StationViewModel>
fullStationList = AutoMapper.Mapper.Map
<IList<Station>, IList<StationViewModel>>
(_loadedStations);
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With