I recently ran into an issue with an asp.net ListView where I wanted to “bind” to an extension method on the entity I was working with.
So, my object looked something like this:
namespace ExtensionMethodBinding { public class MyCustomObject { public string Property1 { get; set; } public string Property2 { get; set; } public string Property3 { get; set; } } } namespace ExtensionMethodBinding.Extensions { public static class MyCustomPropertyExtensions { public static string SomeExtensionMethod(this MyCustomObject instance) { return String.Format("{0} - {1} - {2}", instance.Property1, instance.Property2, instance.Property3); } } }
I deliberately put the extension method in a different namespace (since that is usually the case).
And the list view item template looks something like this:
<ItemTemplate> <tr> <td> <%# Eval("Property1") %> </td> <td> <%# Eval("Property2") %> </td> <td> <%# Eval("Property3") %> </td> <td> <%# ((MyCustomObject)Container.DataItem).SomeExtensionMethod() %>' /> </td> </tr> </ItemTemplate>
And when running it, this little error message turns up:
“CS0246: The type or namespace name ‘MyCustomObject’ could not be found (are you missing a using directive or an assembly reference?)”
I finally figured it out, you have to add a couple of things at the top of the page for it to understand the extension method syntax, like this:
#1 by Best cellulite cream on June 2, 2010 - 23:58
Suitably done.
You have a nice blog.
Thank you for posting.
#2 by Johan Leino on June 3, 2010 - 19:15
Thanks for great feedback!