SunQuest
 
       .NET
  Home arrow .NET arrow Page 4 - Generics and Interface-Based Programming
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
Moblin 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
IBM developerWorks
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
.NET

Generics and Interface-Based Programming
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2007-06-07

    Table of Contents:
  • Generics and Interface-Based Programming
  • Deriving from a Generic Interface
  • Generic Interfaces as Operators
  • Generic Derivation Constraints

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Generics and Interface-Based Programming - Generic Derivation Constraints


    (Page 4 of 4 )

    When a generic class constrains one of its type parameters to derive from an interface, the client may provide as a specific type parameter a particular implementation of the interface:

      public class ListClient<L,T> where L : IList<T>
     
    {
        public void ProcessList(L list)
        {...}
     
    }
      public class NumberList : IList<int>
      {...}

      ListClient<NumberList,int> client = new ListClient<NumberList,int>();
      NumberList numbers = new NumberList();
      client.ProcessList(numbers);

    However, you can also satisfy the constraint by specifying as a type parameter the very interface the type parameter is constrained against, not a particular implementation of it:

      public class ListClient<L,T> where L : IList<T>
     
    {
        public void ProcessList(L list)
        {...}
     
    }
      public class List<T> : IList<T>
      {...}

      ListClient<IList<int>,int> client = new ListClient<IList<int>,int>();
      IList<int> numbers = new List<int>();
      client.ProcessList(numbers);

    or even:

      public class AnotherClient<U>
      {
        ListClient<IList<U>,U> m_ListClient;
      }

    This helps to separate the client code from particular interface implementations.

    Generics, Interfaces, and Casting

    The C# compiler will only let you implicitly cast generic type parameters to object, or to constraint-specified types, as shown in Example 3-11. Such implicit casting is of course type-safe, because any incompatibility is discovered at compile time.

    Example 3-11.  Implicit casting of generic type parameters

    public interface ISomeInterface
    {...}
    public class BaseClass
    {...}
    public class MyClass<T> where T : BaseClass,ISomeInterface
    {
     
    void SomeMethod(T t)
     
    {
        ISomeInterface obj1 = t;
        BaseClass      obj2 = t;
        object         obj3 = t;
      }
    }

    The compiler will let you explicitly cast generic type parameters to any other interface, but not to a class:

      public interface ISomeInterface
      {...}
      public class SomeClass
      {...}
      public class MyClass<T>
      {
       
    void SomeMethod(T t)
       
    {
          ISomeInterface obj1 = (ISomeInterface)t;//Compiles
          SomeClass      obj2 = (SomeClass)t;  //Does not compile
        }
      }

    Such explicit casting is dangerous, because it may throw an exception at runtime if the specific type parameter used does not support the interface to which you explicitly cast. Instead of risking a casting exception, a better approach is to use theisandasoperators, as shown in Example 3-12. You can useisandas both on naked generic type parameters and on generic classes with specific parameters.

    Example 3-12.  Using is and as operators on generic type parameters

    public interface IMyInterface
    {...}
    public interface ISomeInterface<T>
    {...}
    public class MyClass<T>
    {
     
    public void MyMethod(T t)
     
    {
        if(t is IMyInterface)
        {...}

        if(t is ISomeInterface<T>)
        {...}
       
    IMyInterface obj1 = t as IMyInterface;
        if(obj1 != null)
        {...}

        ISomeInterface<T> obj2 = t as ISomeInterface<T>;
        if(obj2 != null)
        {...}
     
    }
    }

    Please check back next week for the conclusion to this article.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This article is an excerpt from the book "Programming .NET Components, Second...
     

    Buy this book now. This article is excerpted from chapter three of Programming .NET Components, Second Edition, written by Juval Lowy (O'Reilly, 2006; ISBN: 0596007620). Check it out today at your favorite bookstore. Buy this book now.

    .NET ARTICLES

    - Commands, Input and the WPF
    - Keyboard and Ink Input with WPF
    - Mouse Input and the WPF
    - Input with Windows Presentation Foundation
    - Introducing LINQ with XML and Databases
    - An Introduction to LINQ
    - Querying LINQ to SQL: Basics
    - Completing a Simple Storefront with LINQ
    - Knowing Your Environment: the System.Environ...
    - Creating the Home Page for a Simple Storefro...
    - LINQ Quickly with Language Integrated Queries
    - Introducing LINQ to SQL Designer using Visua...
    - Beginning LINQ to SQL Using Visual Studio 20...
    - Coding an AjaxPro.NET Based Search Engine fo...
    - Building an AjaxPro.NET Based Search Engine ...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway