Exploring C# 3.0: Listing 2: C#: Add New Logical Functionality

Extension methods let you add logical functionality to existing classes. You control available extension methods through references and namespace using statements.

public static class XmlExtensionMethods
{
   public static string GetString(
      this XAttribute attribute)
   {
      if (attribute == null)
      {
         return string.Empty;
      }
      return attribute.Value;
   }

   public static Int32 GetInt32(
      this XAttribute attribute)
   {
      if (attribute == null)
      {
         return 0;
      }
      var retValue = 0;
      Int32.TryParse(attribute.Value, 
         out retValue);
      return retValue;
   }
}

public static class StringExtensionMethods
{
   public static bool EqualsIgnoreCase(
      this string text1, string text2)
   {
      return text1.Equals(text2, 
         StringComparison.InvariantCultureIgnoreCase);
   }
}
comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.