Generic class<T> with constructor to choose the type

  • A+
Category:Languages

I have three classes that have all the same named Properties. Let's say the classes are Sword, Bow and Hammer -- and the properties are Damage and Range. How could I instantiate a class of Weapon<T> with a constructor where I pass an int to choose the Type of this class?

I am not sure if this is even the right way to do what I want to.

public class Weapon<T> { }  public  class Sword {     public int Damage { get => 10; }     public int Range { get => 12; } }  public class Bow {     public int Damage { get => 8; }     public int Range { get => 28; } }  public class Hammer {     public int Damage { get => 15; }     public int Range { get => 8; } } 

 


What you´ve described is known as factory-pattern. You have some factory that is able to instantiate other objects, in your case depending on an integer:

class WeaponFactory {     public static IWeapon CreateWeapon(WeaponType type)     {         switch type:             case WeaponType.Sword: return new Sword();             case WeaponType.Hammer: return new Hammer();             case WeaponType.Bow: return new Bow();             default: throw new ArgumentException("Unknown weaponType");     } } enum WeaponType { Sword, Hammer, Bow } interface IWeapon {     int Damage { get; }     int Range { get; } } 

Finally all your classes should implement that interface. Now you can easily create instances with the following code:

var hammer = WeaponFactory.CreateWeapon(WeaponType.Hammer); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: