I’ve got a base Class ScenBase and a derived class ScenC. I have a class HexC derived form the base class Hex. I also have a class UnitC derived from the base class Unit. I can set an array of Hex to point to an array of HexC, but the compiler won’t let me set a List of Unit to point to a list of UnitC:
// The Core Database for the game scenario.
// Theoretically multiple secenarios can be loaded
// into memory at the same time.
[Serializable]
public class ScenC : ScenBase
{
public bool playable { get; set; }
public HexC[,] hexCs { get; private set; }
public List<UnitC> unitCs { get; private set; }
// A database for every user and AI entity.
public List<ScenV> chViews { get; private set; }
public List<string> characters { get; private set; }
public ScenC(int xDimI, int yDimI) : base (xDimI, yDimI)
{
playable = false;
chViews = new List<ScenV>();
characters = new List<string>();
characters.Add("Supreme");
hexCs = new HexC[xDim, yDim];
hexs = hexCs; //this line complies fine
newHex = (int x, int y) => new HexC(this, x, y);
unitCs = new List<UnitC>();
// **This line won't compile**
unitCs = units;
Init();
}
}
Here are the fields properties for the base class ScenBase:
[Serializable]
public abstract class ScenBase
{
public Hex[,] hexs;
public List<Unit> units { get; protected set; }
public DateTime currGameTime { get; set; }
public int xDim { get; set; }
public int yDim { get; set; }
public double scale { get; protected set; }
protected delegate Hex NewHex(int x, int y);
protected NewHex newHex;
//Rest of Class not shown for simplicity
}
Why Can’t I set a List<Hex> to a List<HexC> when that follows the “is a” implicit cast rule, but I can set array to array
This is not possible.
Had it been possible, you would have been able to add a different derived type to the list.
For example:
What you’re asking for is called covariance; it’s only possible for immutable interfaces (such as
IEnumerable<T>)