C#
  Home arrow C# arrow Page 2 - C# 3.0 Extension Methods
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  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 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? 
C#

C# 3.0 Extension Methods
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2008-11-06

    Table of Contents:
  • C# 3.0 Extension Methods
  • Ambiguity and Resolution
  • Anonymous Types (C# 3.0)
  • Attributes

  • 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


    C# 3.0 Extension Methods - Ambiguity and Resolution


    (Page 2 of 4 )

    Namespaces

    An extension method cannot be accessed unless the namespace is in scope. Consider the extension method IsCapitalized in the following example:

    IsCapitalized in the following example:An extension method cannot be accessed unless the namespace is in scope. Consider the extension method IsCapitalized in the following example:

      using System;

      namespace Utils
     
    {
        public static class StringHelper
        {
         
    public static bool IsCapitalized (this string s)
         
    {
            if (string.IsNullOrEmpty(s)) return false;
            return char.IsUpper(s[0]);
         
    }
        }
      }

    To useIsCapitalized, the following application must importUtils, in order to avoid a compile-time error:

      namespace MyApp
      {
       
    using Utils;

        class Test
       
    {
          static void Main()
          {
           
    Console.WriteLine("Perth".IsCapitalized());
          }
        }
      }

    Extension methods versus instance methods

    Any compatible instance method will always take precedence over an extension method. In the following example, Test’s Foo method will always take precedence—even when called with an argument x of type int:

      class Test
      {
        public void Foo (object x) { }     // This method always wins
      }

      static class Extensions
      {
        public static void Foo (this Test t, int x) { }
      }

    The only way to call the extension method in this case is via normal static syntax; in other words,Extensions.Foo(...).

    Extension methods versus extension methods

    If two extension methods have the same signature, the extension method must be called as an ordinary static method to disambiguate the method to call. If one extension method has more specific arguments than another, the more specific extension method takes precedence over the less one. For example:

      static class StringHelper
      {
        public static bool IsCapitalized (this string s)
        {
          if (string.IsNullOrEmpty (s)) return false;
          return char.IsUpper (s[0]);
        }
      }

      static class ObjectHelper
      {
        public static bool IsCapitalized (this object s)
        {
         
    return true;
        }
      }

    Usage:

      // Calls StringHelper.IsCapitalized
      Console.WriteLine("Perth".IsCapitalized());

      // Explictly calling ObjectHelper.IsCapitalized
      Console.WriteLine(ObjectHelper.IsCapitalized("Perth"));

    Extension Methods on Interfaces

    Extension methods can apply to interfaces:

      using System; using
      System.Collections.Generic;

      static class Test
      {
        static void Main()
        {
         
    var strings = new string[] { "a", "b", null, "c"};
          foreach (string s in strings.StripNulls())
            Console.WriteLine(s);
        }
        static IEnumerable<T> StripNulls<T> (this IEnumerable<T> seq)
        {
          foreach (T t in seq)
            if (t != null)
              yield return t;
        }
      }

    More C# Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "C# 3.0 in a Nutshell, Third Edition, A...
     

    Buy this book now. This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.

    C# ARTICLES

    - Coding a CRC-Generating Algorithm in C
    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek