Reputation: 1
When I was trying to add items to the generic list, I am unable to add, code I am using has been provided above, could any one suggest on this.
Vehicle v2 = new Vehicle(2, false, "car", 50);
Vehicle v3 = new Vehicle(3, false, "suv", 100);
Vehicle v4 = new Vehicle(4, false, "suv", 100);
public List<T> Initialize<T>() where T : Vehicle, new()
{
List <T> veh_list= new List<T>();
//veh_list.Add(new T(1, false, "car", 50));
veh_list.Add(v2);
veh_list.Add(v3);
veh_list.Add(v4);
return veh_list;
}
Error : Cannot Convert from Vehicle to T.
Upvotes: 0
Views: 210
Reputation: 888177
Your method shouldn't be generic in the first place.
Making the method generic would let callers write Initialize<Truck>()
, and a List<Truck>
cannot contain Vehicle
s.
You should make a normal non-generic method that returns a List<Vehicle>
.
Upvotes: 3