Share via


Extension methods cannot be dynamically dispatched ...

Question

Friday, March 23, 2012 11:10 PM

Hello,

I have the following method in a library class:

conn.Execute(String sql, dynamic param = null, IDbTransaction transaction = null, Int32? commandTimeout = null, CommandType? commandType = null)

On a method I am creating I want to call this method as follows:

public Int32 Run(String sql, dynamic param = null) {
  return _conn.Execute(sql, param); 
}

But I get the following error:

 'System.Data.IDbConnection' has no applicable method named 'Execute' 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.  

If I remove param then it works fine ... What is the correct way to solve this?

I am just trying to create a method that does exactly the same that the other but with a different name ...

And is there another way to do this in such cases?

Thank You,

Miguel

All replies (1)

Saturday, March 24, 2012 4:09 PM âś…Answered | 1 vote

The Execute method you are calling is an extension method.  An extension method is simply a compiler trick to make a static method appear as an instance method.  It helps expose functionality on types via Intellisense.  Under the hood it is still just a static method call - the compiler does the translation.

Call the Execute method by invoking the method on the static class and passing conn as the first parameter.

//Assuming
public static class SomeClass
{
   public static void Execute ( this IDbConnection source, string sql, ... )
}

//Your code
SomeClass.Execute(conn, sql, param);

Michael Taylor - 3/24/2012
http://msmvps.com/blogs/p3net