I am practicing in OOP and I have created a simple console application where I have 3 factions and every faction must have it's own Army, and every distinct army can contain certain units.
I used interfaces and inheritance, but I have some problem in generic conversions. I can't figure out how to solve this problem in a right way, please help me.
Here is the code.
This is my Army
and Units
implementation.
public abstract class Unit<T> : IUnit<T> where T : Faction {
public string UnitName { get; set; }
public IFaction Nation { get; set; }
public Unit(string name) {
UnitName = name;
}
public virtual void PrintUnitInfo() {
Console.WriteLine($"UnitName: {UnitName}\nNation: {Nation}\n");
}
}
public interface IUnit<T> where T : IFaction {
string UnitName { get; set; }
IFaction Nation { get; set; }
void PrintUnitInfo();
}
public class Army<T> where T : IFaction {
private List<IUnit<T>> units = new List<IUnit<T>>();
public void Recruit(IUnit<T> unit) {
units.Add(unit);
}
public void PrintFactionName() {
Console.WriteLine(nameof(IFaction));
}
}
And here is the Faction
implementation.
public abstract class Faction : IFaction {
public string Name { get; }
public int Minerals { get; set; }
public Army<Faction> Army { get; set; }
public Faction(string name, Army<Faction> army) {
Name = name;
Minerals = 100;
Army = army;
}
public virtual void Greetings() {
Console.WriteLine("Printing FucntionInfo from BaseFaction");
}
public virtual void PrintUnitsInfo() {
Console.WriteLine("Printing UnitsInfo from BaseFaction");
}
}
public interface IFaction {
string Name { get; }
Army<Faction> Army { get; set; }
int Minerals { get; set; }
void Greetings();
void PrintUnitsInfo();
}
And finally here is the usage the where compiler shows an error:
Cannot convert from 'Army<Zerg>' to 'Army<Faction>".
public static void Main(string[] args) {
Faction zerg = new Zerg("Zerg", new Army<Zerg>());
zerg.Army.PrintFactionName();
Console.ReadKey();
}
}
public class Zerg : Faction {
public Zerg(string name, Army<Faction> army) : base(name, army) { }
}
Sorry if question looks very big and confusing, but I can't make my problem clear in other way.