Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method with generic parameter called from subclass instance

Tags:

c#

generics

Here is my issue:

public class User
{
    public virtual void Save()
    {
        Connection.Save(this);
    }
}

public class Administrator : User
{
}

public static class Queries
{
    public static void Save<T>(this IDbConnection cn, T entity)
    {
        var properties = Mapper<T>.GetProperties();
        // other code
    }
}

public static class Mapper<T>
{
    public static IList<Property> GetProperties()
    {
        var type = typeof(T);
        // other code
    }

    // other T-dependent methods
}

When user.Save() is called, it works fine, however for admin.Save() the generic parameter T is User, not Administrator, so reflection inside GetProperties() returns user properties.

I can make it work by overloading Mapper<T>.GetProperties(instance.GetType()), but this seems not semantically correct, as having two types leads to ambiguity.

Is there a better way to resolve the issue? Thanks.

like image 351
Herman Kan Avatar asked Mar 10 '26 23:03

Herman Kan


1 Answers

Generic type arguments are resolved at compile time, not at runtime, there's nothing that can be done about that.
You need to determine the type by using GetType() on an instance of the object to get the runtime type, so you might have to rethink your design a bit keeping that in mind. Maybe using generics isn't the best thing to do in this case.

like image 121
Botz3000 Avatar answered Mar 12 '26 12:03

Botz3000



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!