Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a class type based on int value

Tags:

c#

generics

Right now, I have an enum like this:

public enum ReferenceType
{
    Language = 1,
    Period = 2,
    Genre = 3
}

Language, Period, and Genre are all entity classes that map back to tables in my database. I also have model classes that map almost 1 to 1 with the entity classes, which I then display in a view.

I also have a service method like this:

List<Model> Get<Model, Entity>()
        where Model : BaseModel
        where Entity : BaseEntity;

I can call it like Service.Get<LanguageModel, Language>() and it will return every row from table Language from my database and automatically convert them into LanguageModels, which I'll then display in my view.

I want to create a wrapper method around the Get() method where you simply need to pass in an integer and it will call my Get() method filling in the entity and model class types automatically. The only problem is I'm having a hard time wrapping my head around the actual implementation behind this.

The pseudo-code would be along the lines of:

  1. Call WrapperGet((int)ReferenceType.Genre)
  2. Wrapper method resolves the entity type (Genre) and model type (GenreModel)
  3. Call the Get() method with the resolved entity and model types, so it'd be Get<GenreModel, Genre>()
  4. Return the results

How would I actually go implementing this in C#?

like image 425
Jay Sun Avatar asked May 25 '26 00:05

Jay Sun


2 Answers

I can't think for a full generic way, I think simplest way is as below:

List<Model> WrapperGet(int type)
{
   switch (type)
   {
      case 1: return Get<LanguageModel, Language>();
      ....
   }
   return null;
}
like image 171
Saeed Amiri Avatar answered May 26 '26 12:05

Saeed Amiri


If you want strongly-typed results, you'll have to forgo the idea of passing an int or enum in, and switch to calling Get directly or making methods like this:

List<LanguageModel> GetLanguages() { return Get<LanguageModel, Language>(); }

If weakly typed works for you, then I'd go with Saeed's solution, but the types need a little changing to work. Model was a generic type in your example, so presumably he meant List<BaseModel> as the return type. But a List<LanguageModel> isn't a List<BaseModel>! You can resolve this by either making it return IEnumerable<BaseModel> or changing Get to return a List<BaseModel>, or change it afterwards with return new List<BaseModel>(Get<...

like image 30
Tim S. Avatar answered May 26 '26 12:05

Tim S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!