deft flux

A portal into the creative workings of David Meyer

Great post by Phil Haack

Phil Haack recently posted a blog entry on duck typing.  Read it here.  It gives a very good explanation of it and some of its advantages.

He also gives a very good example of a use for duck typing using my library.  His example demonstrates a feature that I like to call variance in class members.  Specifically, when duck casting an object to an interface, the object need not even implement the interface exactly.  Rather, its members may differ from those defined in the interface as long as the parameter types, return types, property types, and event delegate types are convertible to one another, which may be so via duck typing, as in his example.  Here is an excerpt from his example: (comments mine)

public interface IHttpContext
{
    // Note that the Request property returns IHttpRequest.
    IHttpRequest Request { get;}
}

public interface IHttpRequest
{
    Uri Url { get;}
}
 

In his example, the sealed class HttpContext is duck casted to IHttpContext.  Here is what some of the code might look like for this class for the sake of demonstration:

public sealed class HttpContext
{
    // Here, however, Request returns HttpRequest.  Duck typing still works because HttpRequest
    // can be duck casted to IHttpRequest, which is actually done behind the scenes when Request
    // is called on the duck casted object through the IHttpContext interface.
        
    public HttpRequest Request { get { ... } }
    
    ...
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by deftflux on Monday, August 20, 2007 7:12 AM
Permalink | Comments (0) | Post RSSRSS comment feed