Herman Kan
Herman Kan

Reputation: 2292

Extension method with generic parameter called from subclass instance

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.

Upvotes: 3

Views: 95

Answers (1)

Botz3000
Botz3000

Reputation: 39600

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.

Upvotes: 3

Related Questions