Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot call extension methods with dynamic params and generics

I am curious to see if anyone else has run into this same issue... I am using Dapper as on ORM for a project and was creating some of my own extension methods off of the IDbConnection interface in order to simplify code, where I ran into (what I found to be) puzzling error.

I will walk through the process I went through.

First, I added an extension method to my project in a static class named DbExtensions like so:

using System.Collections.Generic;
using System.Data;
using System.Linq;

public static class DbExtensions
{
    public static T Scalar<T>(
        this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
    {
        var ret = cnn.Query<T>(sql, param as object, transaction, buffered, commandTimeout, commandType).First();
        return ret;
    }
}

This creates a compile error with the following description:

'System.Data.IDbConnection' has no applicable method named 'Query' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

This is fine, and the error is actually rather helpful as it even tells me how to fix it. So I then try:

using System.Collections.Generic;
using System.Data;
using System.Linq;

public static class DbExtensions
{
    public static T Scalar<T>(
        this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
    {
        var ret = SqlMapper.Query<T>(cnn, sql, param, transaction, buffered, commandTimeout, commandType).First();
        return ret;
    }
}

and it compiles correctly. Something strange is going on though. In Visual Studio, if I take the return value of SqlMapper.Query<T> which should be IEnumerable<T>, and I try to operate on it, Visual Studio gives me NO intellisense properties except for those inherited via object.

Thinking I am just doing something that intellisense isn't smart enough to figure out, I go on my merry way... until I actually try to RUN the code.

When I try to run it, it trips up where I am calling .First() with the following error:

'System.Collections.Generic.List<MyNameSpace.MyClass>' does not contain a definition for 'First'

Now THIS error, I thought was interesting... After banging my head for a while, I realized the first argument was complaining about the dynamic typing...

I suppose this error is occurring because the compiler cannot build the Generic Template because it does not know that Query is returning IEnumerable<T> as it is being executed in the DLR? I would love to hear someone explain this who was knowledgeable. I have essentially found two ways to fix it:

  • Cast the dynamic param to an object
  • Cast the returned value to an IEnumerable<T>

using System.Collections.Generic;
using System.Data;
using System.Linq;

public static class DbExtensions
{
    public static T Scalar<T>(
        this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
    {
        var ret = SqlMapper.Query<T>(cnn, sql, param as object, transaction, buffered, commandTimeout, commandType).First();
        return ret;
    }
}

using System.Collections.Generic;
using System.Data;
using System.Linq;

public static class DbExtensions
{
    public static T Scalar2<T>(
        this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
    {
        var ret = ((IEnumerable<T>)SqlMapper.Query<T>(cnn, sql, param, transaction, commandTimeout, commandType)).First();
        return ret;
    }
}

IN SUMMARY:

I am new to working through the qwerks of the DLR and there seem to be some caveats to keep in mind when messing around with dynamic + Generics...?

I know this isn't a question per-se, but when I actually started writing this I didn't know what was going on and I figured it out in the process! I thought it might help someone else with similar issues though...

like image 458
Leland Richardson Avatar asked Jun 13 '12 02:06

Leland Richardson


1 Answers

As suggested, I will try and Answer my question in an actual answer... (Now that it's been 8 hours)

My understanding of the issue is this:

  • As described in the referenced question, dynamic types do not have extension methods available to them, but extension methods can be used normally (as instance methods), just as they would be without the this keyword...

for instance:

dynamic list = someListObject;

var item = list.First(); //this will not compile

var item = Enumerable.First(list);  //this will compile

As Jon Skeet has pointed out in this answer this is all by design and part of the DLR implementation - where if any invocation has a dynamic argument it will have a return type considered dynamic.

  • For similar reasons, using dynamic variables in extension methods is a bit wonky...

public static Enumerable<T> ExtensionMethod(this ExtendedObject p1, dynamic p2) {
    //Do Stuff
}

dynamic y = something;
var x = new ExtendedObject();

//this works
var returnedEnumerable = x.ExtensionMethod(y); 

//this doesn't work
var returnedValue = x.ExtensionMethod(y).SomeEnumerableExtensionMethodLikeFirst() 

To make the above example work you can do one of the following:

//cast dynamic as object
var returnedValue = x.ExtensionMethod(y as object).First(); 
//cast returned object
var returnedValue = ((IEnumerable<KnownType>)x.ExtensionMethod(y)).First(); 
like image 79
Leland Richardson Avatar answered Oct 22 '22 15:10

Leland Richardson