Partial Type Inference in .Net

When designing fluent APIs, one issue that comes up is partial type inference.  If a method has two type parameters, there is no way to call it and only specify one of the type parameters (and leave the other inferred by the compiler)

For example, suppose we are creating a type-safe wrapper around a parameterized SqlCommand.
Ideally, it would be called like this:

using(DbConnection connection = ...) {
    var result = connection.ExecuteScalar<int>(
        "SELECT COUNT(*) FROM TableName WHERE Modified > someDate",
        new { someDate }
    );
}

Where the generic parameter specifies the return type.

In order to implement this efficiently, one would create methods at runtime which add DbParameters for each property in the anonymous type, and store them in a static generic class.   
It would look something like this:

static class Extensions {
    public static void AddParams<TParam>(this IDbCommand command, 
                                         TParam parameters)
        where TParam : class { 
        if (parameters != null) 
            ParamAdders<TParam>.Adder(command, parameters);
    }
    static class ParamAdders<TParam> where TParam : class {
        public delegate void ParamAdder(IDbCommand command,
                                        TParam parameters);
        public static readonly ParamAdder Adder = CreateParamAdder();

        private static ParamAdder CreateParamAdder() { 
            return ...; 
        }
    }
}

However, that requires that the ExecuteScalar extension method take TParam as a generic parameter.  Since anonymous types can only be passed as generic parameters via type inference, this makes it impossible to pass the return type as a generic parameter.

To fix this issue, we can split the generic parameters across two methods.  We can change the extension method to take a single generic parameter, and return a generic class with a method that takes the other generic parameter.

For example:

static class BetterExtensions {
    public static SqlStatement<T> Sql<T>(this IDbConnection conn,
                                         string sqlText) { 
        return new SqlStatement<T>(conn, sqlText); 
    }
}
class SqlStatement<TReturn> : IHideObjectMembers {
    public SqlStatement(IDbConnection connection, string sql) { 
        Connection = connection; 
        Sql = sql;
    }
    public IDbConnection Connection { get; private set; }
    public string Sql { get; private set; }

    public TReturn Execute() { return Execute<object>(null); }
    public TReturn Execute<TParam>(TParam parameters)
         where TParam : class {
        return ...;
    }
}

I use an IHideObjectMembers interface to hide the methods inherited from Object from IntelliSense.  Note that the interface must be defined in an assembly outside of your solution. (or, to be more precise, that isn’t a Project reference)

This version would be called like this:

using(IDbConnection connection = null) {
    var result = connection.Sql<int>(
        "SELECT COUNT(*) FROM TableName WHERE Modified > someDate"
    ).Execute(new { someDate });
}

The return type is specified explicitly in the call to Sql<T>(), and the parameter type is passed implicitly to Execute<TParam>().

25 comments:

It's worth taking a longer look at this article. Tracey

I advise you to check this out if you want to read college essay examples. I had such experience recently, by the way

This is such an extraordinary asset, to the point that you are giving and you give it away for nothing. I adore seeing blog that comprehend the quality. Im happy to have discovered this post as its such a fascinating one! I am dependably watchful for quality posts and articles so i assume im fortunate to have discovered this!
Play now friv games for free!

Instructional exercise is simply awesome..It is truly useful for a novice like me.. I am a standard adherent of your blog. Actually quite educational post you shared here. Domyassignmentforme

The ultimate goal of online sociology research paper writing services is to provide Sociology Assignment Writing Services and sociology essay writing services since most sociology term paper writing service students lack time to complete their custom sociology coursework writing services.

Event management assignment writing services are essential and they have become very popular for those seeking event management essay writing help services since most of them seek Event Management Writing Services.

At present, in a conjuring of a conventional technique, you either need to indicate the entirety of the sort contentions or none of them, in the last case contingent upon the compiler to gather them for you. Do My Assignment For Me

Your recommendations really work in practice. I am currently working on an literary analysis essay and actively using this advice. I hope others will also take advantage of this opportunity.

The upsides of utilizing the organizer board are likewise talked about in this article, for which the expense of introducing this framework is legitimized for an energetic angler. top cleaning companies in dubai

<a href="https://heritagedesignbuildgroup.com/residential-design-services/>residential building design and construction - heritagedesignbuildgroup</a> is the most potential service given by heritage group with most excellence.

Call girls in Guwahati ready to serve you with the best 24x7 call girl service
in top-rated hotels at an affordable fixed rate. Book Guwahati call girl now.
Call Girl
Call Girl
Call Girl
Call Girl

Partial Type Inference in .Net is a standout amongst other blog that I have at any point seen so far go here Write My Assignment UK for subtleties.

Thank you for sharing good content. I found your blog on google search it’s very helpful for me.
3Movierulz

I'm almost certain there was an issue in regards to recursive conventional, yet I can't track down it. Without recursive kind boundaries, I think 2 is better in light of the fact that is less verbose, since verbosity is important for the issue here leather jacket for sale. Be that as it may, with recursive sort boundaries, I figure 1 would fit better.

Develops a sort comprising of all properties of Best Graphic Illustrators Type set to required. Something contrary to Partial.,Constructs a sort with all properties of Type set to readonly, which means the properties of the built kind can't be reassigned.

We are dedicated to creating the best environment for the weightlifting community. We have a unique set-up for training that provides fitness on the platform which is not available in a regular gym. We have the expertise to not just train, but also improve and fix mobility/ stability issues of all age groups. We are an exclusive weightlifting training center, bringing together beginners, athletes & coaches with one goal in mind. Lift With Mobility

Sweet blog! I found it while browsing on Yahoo News. Do you have any tips on how to get listed in Yahoo News? do my college homework I’ve been trying for a while but I never seem to get there! Thank you

Our mission is to create human connection by inspiring people to express themselves. We believe your custom T-shirt designs can ignite a movement. We're working to create a more connected and engaged world that supports and celebrates everyone's unique identity, thoughts, and passions. The Bold Words

Owned and operated by Trey McLaughlin, a native Charlestonian, Best Consignment Services For Firearms was founded to provide concierge FFL/NFA services to a select clientele. Trey is an avid sportsman, hunter and gun enthusiast. Trey loves history and has a specific focus on World War 2 history and firearms.

Huckleberry is an online general merchandising store that specializes in printing one-of-a-kind creative items. We print general merchandise like T-shirts, Mugs, Hoodies, Car Bumpers, and other items. Our customized texts contain Bold statements that are unique and thought-provoking. Huckleberry Tees

Programs and Services are designed to provide comprehensive year-round afterschool and summer enrichment program curricula for school-age youth (K-12) to promote and increase mastery of academic skills, knowledge, and content of core academic subjects. Social enterprise sector

to the point that you are giving and you give it away for nothing. extraordinary asset, UK's Top-Rated and Students' Most Favorite Assignment Writing services uk is Here to Offer Expert Help in Most Affordable Prices with a Guarantee to an A or A+ Grade
Assignment writing services UK

have well-qualified writers to write different types of academic papers. Buy Assignments Online We accept requests for essays, dissertations, course research papers, and term papers

Post a Comment