Reputation: 37
Using generics, how do I call a method twice but each time the model parameter is a different type. The first time, the model parameter is of type ViewModel1 and the second time the model parameter is of type ViewModel2. As you can see, the first parameter of the method is hard coded as ViewModel1, I want this to be of type T, so I can use ViewModel1 or ViewModel2. When I change the method to use generics it complains that T does not contain a definition for PoolItems.
SetPoolItems(model, pools); // ViewModel1, IList<PoolViewModel>
SetPoolItems(model, pools); // ViewModel2, IList<PoolViewModel>
private static void SetPoolItems(ViewModel1 model, IList<PoolViewModel> pools)
{
model.PoolItems = pools
.Select(p => new SelectListItem
{
Value = p.Id.ToString(),
Text = p.Name,
}).ToList();
}
Upvotes: 0
Views: 60
Reputation: 82096
You don't need Generics at all, you could have both models implement a common interface instead e.g.
interface IViewModel
{
IList<SelectListItem> PoolItems { get; set; }
}
public class ViewModel1 : IViewModel
{
...
}
public class ViewModel2 : IViewModel
{
...
}
private static void SetPoolItems(IViewModel model, IList<PoolViewModel> pools)
{
...
}
Upvotes: 2