Blog

  • Home /
  • Blog /
  • Linfu Duck Typing Part 1 – Revealing Secrets

Linfu Duck Typing Part 1 – Revealing Secrets

April 16, 2010

Don’t you just hate it when a class in the .NET Framework or another third-party library or framework provides that particular feature you’re looking for only to realize that this class has not been made accessible? One blatant example of this is the SqlCommandSet class in the System.Data.SqlClient namespace.

One can use reflection in order to access and use this private class. An even better and more efficient approach would be to use delegates instead. But there’s also another simple and elegant solution which I briefly mentioned in a previous post namely duck typing.

Now in order to access the SqlCommandSet class we need to define an interface with all of the methods we want to access from our code. Reflector can come in handy in this case to determine which particular methods we need.

This is pretty much what we need from a SqlCommandSet. Now we can create a factory class for creating instances of the SqlCommandSet class.

The System.Data assembly is loaded and the type of the SqlCommandSet is determined in the constructor of the factory class. In the factory method itself we first create an instance of the SqlCommandSet class and then use LinFu’s DynamicObject to ‘cast’ it to our ISqlCommandSet interface. And this is pretty much it. Now we can use a SqlCommandSet at will.

public interface ISqlCommandSet : IDisposable
{
    SqlConnection Connection { get; set; }

    void Append(SqlCommand command);
    Int32 ExecuteNonQuery();
}

Again I’d like to mention that I’ve been using the DynamicObject class from Linfu 1.0 which you can download here.

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be