Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic casting to call appropriate overload

Tags:

c#

generics

I have a public generic method which accepts one generic parameter. I also have one several private methods accepting concrete type arguments that i'm calling from generic method. To better describe my problem take a look at the code below:

    public void Save<T>(T entity) where T : class
    {
        if(entity is LibraryItem)      Save(entity as LibraryItem);
        else if(entity is Folder)      Save(entity as Folder);
        else if(entity is ProductType) Save(entity as ProductType);
        else if(entity is ProcessName) Save(entity as ProcessName);
    }

And private methods:

private void Save(ProcessName proc){}
private void Save(ProductType type){}
private void Save(Folder folder){}
...

Looking at the code, I really don't like the solution, checking for every possible type looks like a bad practice imho. So I wonder if there is any cleaner solution to my problem? Maybe it's possible to cast T dynamically at runtime and call appropriate private method?

like image 768
Davita Avatar asked Sep 15 '25 23:09

Davita


2 Answers

Use runtime type definition:

public void Save<T>(T entity) where T : class
{
    Save((dynamic)entity);
}

private void Save(LibraryItem lib){}
private void Save(ProcessName proc){}
private void Save(ProductType type){}
private void Save(Folder folder){}

You also will need one method with parameter of object type to handle case where entity is not LibraryItem, ProcessName, ProductType, or Folder:

private void Save(object obj) {  }
like image 105
Sergey Berezovskiy Avatar answered Sep 17 '25 13:09

Sergey Berezovskiy


You're on the right track. Use the dynamic keyword to get runtime overload resolution:

Save((dynamic)entity);

Normally overload resolution is done during compile time on the static type (which is object for a generic type). By casting to dynamic you defer the resolution to run time and the runtime type is used instead of the static type.

like image 24
Anders Abel Avatar answered Sep 17 '25 12:09

Anders Abel