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?
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) { }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With