.logik.
.logik.
CC#
Created by .logik. on 3/6/2023 in #help
✅ Help with non-nullable field must contain a non-null value when exiting constructor.
Following an online tutorial and trying to resolve nullable reference warnings (the tutorial was before nullable reference types were introduced). I have a GameSession class with the constructor defined as
public GameSession()
{
CurrentPlayer = new Player
{
Name = "MyName",
Gold = 1000000,
CharacterClass = "Ranger",
HitPoints = 10,
ExperiencePoints = 0,
Level = 1,
};

CurrentWorld = WorldFactory.CreateWorld();

CurrentLocation = CurrentWorld.LocationAt(0, -1);
}
public GameSession()
{
CurrentPlayer = new Player
{
Name = "MyName",
Gold = 1000000,
CharacterClass = "Ranger",
HitPoints = 10,
ExperiencePoints = 0,
Level = 1,
};

CurrentWorld = WorldFactory.CreateWorld();

CurrentLocation = CurrentWorld.LocationAt(0, -1);
}
The error is regarding the backing field private Location _currentLocation which is set using the property
public Location CurrentLocation
{
get => _currentLocation;
set
{
_currentLocation = value;
OnPropertyChanged();
}
}
public Location CurrentLocation
{
get => _currentLocation;
set
{
_currentLocation = value;
OnPropertyChanged();
}
}
Furthermore the LocationAt method is non-nullable defined as
public Location LocationAt(int xCoordinate, int yCoordinate)
{
foreach (Location loc in _locations)
{
if (loc.XCoordinate == xCoordinate && loc.YCoordinate == yCoordinate)
{
return loc;
}
}

throw new LocationNotFoundException($"Location at x:{xCoordinate} y:{yCoordinate} does not exist");
}
public Location LocationAt(int xCoordinate, int yCoordinate)
{
foreach (Location loc in _locations)
{
if (loc.XCoordinate == xCoordinate && loc.YCoordinate == yCoordinate)
{
return loc;
}
}

throw new LocationNotFoundException($"Location at x:{xCoordinate} y:{yCoordinate} does not exist");
}
So my question is, why am I still getting the warning and what is the best approach to fixing it? As I understand it, the compiler already knows that LocationAt will return a Location and the backing field _currentLocation should be set by the CurrentLocation property in the constructor. Why does it still think currentLocation is null when exiting constructor? TIA
13 replies
CC#
Created by .logik. on 11/26/2022 in #help
Application called an interface that was marshalled for a different thread?
31 replies