Within my MVC3 app I am trying to create a general class (named DdlGet below) to call that gets records for a drop down list (DDL). The code below does as intended however I think I’m overbaking the use of the Generic type T – specifically the line indicated below with the ‘//**’
I have the following code in my Controller
private readonly IGeneralReferenceRepository<StatusType> statusTypeRepository;
...
public StatusController() : this(...new StatusTypeRepository()) {}
public StatusController(...IGeneralReferenceRepository<StatusType> statusTypeRepository)
{
...
this.statusTypeRepository = statusTypeRepository;
}
...
public ViewResult Index()
{
...
//**** The line below passes a variable (statusTypeRepository) of the Generic
//**** type (StatusType) and additionally calls the class (Helper<StatusType>)
//**** with the Generic
indexViewModel.StatusTypes = Helper<StatusType>.DdlGet(statusTypeRepository);
Then in my repository (this defines the implementation for getting the records for the DDL from the database [via Entity Framework method]) – note the general reference Generic interface (IGeneralReferenceRepository)
public class StatusTypeRepository : IStatusTypeRepository, IGeneralReferenceRepository<StatusType>
{
...
public IQueryable<StatusType> All
{
get { return context.StatusTypes; }
}
I have an interface (which corresponds to the All method being called above)
public interface IGeneralReferenceRepository<T>
{
IQueryable<T> All { get; }
}
And a helper class to get the drop down list records and place into the SelectList
public class Helper<T>
{
public static SelectList DdlGet(IGeneralReferenceRepository<T> generalReferenceRepository)
{
return new SelectList(generalReferenceRepository.All, ...);
}
}
The issue I have is the line indicated in the first code block above – i.e. the call to the eventual implementation that populates the SelectList
indexViewModel.StatusTypes = Helper<StatusType>.DdlGet(statusTypeRepository);
As explaned above in the comment (prefixed with //**) this passes a Generic statusTypeRepository which defines the type via the line:-
private readonly IGeneralReferenceRepository<StatusType> statusTypeRepository;
However I’m already defining the type in the Helper Generic class (i.e. the Helper class)
The question I have is can I derive one from the other rather than specifying the generic twice in the call. i.e. can I derive the type specified in the statusTypeRepository from the Helper class type or vice versa
Many thanks
Travis
Rather than having the type parameter on your
Helperclass, you could put it on the methods within like this:Then you can just do
and the compiler will handle the type inference.