.NET Framework - Extension methods cannot be dynamically dispatched ...

Asked By Shapper on 24-Mar-12 06:31 AM
Hello,

On a class library I have the following extension:

public static Int32 Execute(this IDbConnection cnn, String sql, dynamic p=
aram =3D null)

I am trying to expose this extension through a method on my class:

public class Repository : IRepository {

private IDbConnection _connection;

public Repository(IDbConnection connection) {
_connection =3D connection;
} // Repository

public Int32 Execute(String sql, dynamic param =3D null) {
return _connection.Execute(sql, param);=20
} // Execute

} // Repository

But I keep getting the following error:

'System.Data.IDbConnection' has no applicable method named 'Execute' but ap=
pears 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.  =20

I tried to change my code in a few ways but no luck ...

Any idea of how to solve this?

Thank You,
Miguel




Peter Duniho replied to Shapper on 24-Mar-12 12:16 PM
Yes.  Do what the error message tells you to do: "Consider casting the
dynamic arguments or calling the extension method without the extension
method syntax."

Given what little code you have posted so far, likely the latter will be the
most fruitful approach in your scenario.
Arne_Vajhøj replied to Shapper on 24-Mar-12 01:26 PM
The error message has two suggestions.

But I think you should go a third route.

I am highly skeptical about you really needing dynamic, so I
would suggest you try whether object or maybe object[] / List
would work just as well for you.

Arne
Shapper replied to Arne_Vajhøj on 25-Mar-12 10:12 AM
mic param =3D null)
t appears to have an extension method by that name. Extension methods canno=
t be dynamically dispatched. Consider casting the dynamic arguments or call=
ing the extension method without the extension method syntax.

Yes, in fact for a 3.0 version there is object[] ...

But I was able so solve it. I just need to use something like:

SqlMapper.Execute( ... )

I forgot that ...

Thank You,
Miguel
Peter Duniho replied to Shapper on 25-Mar-12 12:05 PM
Just as the error message told you to do.


Humans forget. That's why it is useful to read the error messages. They
contain reminders.
Arne_Vajhøj replied to Shapper on 25-Mar-12 08:59 PM
If SqlMapper is the class of your extension method then that is
one of the suggestions in the error message.

But even though you now have gotten it to compile, then
I still can not see any reason for using dynamic.

Arne