I have the following objects
class Magazine
{
String intendedGunId {get;}//Returns some Gun.weaponID;
int size {get;}
//Implementation
}
class Gun
{
public enum FireModes
{
Bolt,
Semi,
FullAuto
}
public FireModes fireMode { get; private set; }
Magazine magazine;
public Magazine reload(Magazine newMag)
{
if (magazine.intendedGunId == newMag.intendedGunID)
{
Magazine temp = magazine;
this.magazine = newMag;
return temp;
}
return newMag;
}
//Other implementation
}
class AKMag : Mag
{
//Implementation
}
class AK : Gun
{
//Implementation
}
I am designing a gun and a magazine that should always be used in said gun for multiple different guns.
I don't think keeping the Magazine variable as T : Magazine
instead of just Magazine is a smart idea, as when reloading, nearly any magazine could be accepted, and it doesn't feel like safe code; I feel like a hacker could easily take advantage of this.
I have tried the following generic:
class Gun<T> where T : Magazine
{
T magazine;
//Other implementation
}
class AK : Gun<AKMag>
{
}
The problem is once I use generics, it becomes impossible to store a Gun<Magazine>
variable, because at some point, the compiler will say "Can not convert from Gun<AKMag>
to Gun<T> where T : Magazine
.
Basically, every gun has its own mag that will only belong to it's gun. I am struggling to implement this correctly, maybe from a lack of understanding of C# generics or C# inheritance.
EDIT: With a gun generic, the following scenario does not work:
Gun<Magazine> someGun;
public void func (Gun<Magazine> gun)
{
this.someGun = gun;
}
//In another class
AK<AKMagazine> someAK;
public void func2 ()
{
func1 (someAK); //Error: "Can not convert from `Gun<AKMag>` to `Gun<T> where T : Magazine`."
}
Edit: I decided that the best way to do this was to check if magazine.GetType() == newMag.GetType() whenever the mag was going to be change, however an interface may work as well.