deft flux

A portal into the creative workings of David Meyer

About the author

David Meyer (a.k.a. "deft flux") is a software developer fluent in C#, C++, Java and others. He also programs in his spare time and enjoys playing instruments and making electronic music.
E-mail me Send mail

Recent comments

Authors

Disclaimer

The opinions expressed by the author are his alone and do not represent any other person or organization unless stated otherwise. The opinions given in comments are solely those of the person who wrote the comment and are not necessarily the opinions of the author of this site. The author of a post is not responsible for the content of its comments.

© Copyright 2008
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 2:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag




Live preview

Friday, November 21, 2008 8:34 AM

Gravatar