Matt Casto's .NET Journal RSS 2.0
 Saturday, March 31, 2007
The support for extending existing types with custom methods in Orcas is something I've been fairly excited about for a while. Extension methods provide way to inject your static own method into someone else's type, where it will appear as if it was an instance method defined on that type.

A Simple Example

In many of my projects, I have enumerations decorated with a description attribute and a static method in a utility class which will return the description of an enum value. This provides a way to have a user friendly description of an enum value. Now I can take that method in the utility class, modify it slightly to be an extension method, and have better looking, more intuitive and highly discoverable code.

Let's say we have an enumeration of report titles.

public enum ReportTitle
{
[EnumDescription("TPS Report")]
TPS,
[EnumDescription("Summary Report")]
Summary,
[EnumDescription("Expense Breakdown Report")]
[EnumDescription("Expense Report")]
ExpenseBreakdown,
Unknown
}

My .NET 2.0 utility method to get enum descriptions looks like this:

public static string GetEnumDescription(Enum enumValue)
{
if (enumValue == null)
return string.Empty;

Type enumType = enumValue.GetType();
Type descType = typeof(EnumDescriptionAttribute);
FieldInfo fi = enumType.GetField(enumValue.ToString());
object[] descAttrs = fi.GetCustomAttributes(descType, false);

// concatenate multiple descriptions
string desc = string.Empty;
foreach (EnumDescriptionAttribute descAttr in descAttrs)
desc += (desc.Length == 0)
? descAttr.Description
: ", " + descAttr.Description;

if (desc == string.Empty)
desc = enumValue.ToString();

return desc;
}

I don't think I really need to show the EnumDescriptionAttribute code or code that gets report titles, because there are no surprised there. As an aside, if anyone wonders why I'm not using System.ComponentModel.DescriptionAttribute, its because that attribute doesn't support multiple decorators on a single type.

This example code re-written with Visual Studio Orcas March CTP looks like this:

public static string Description(this Enum enumValue)
{
if (enumValue == null)
return string.Empty;

var enumType = enumValue.GetType();
var descType = typeof(EnumDescriptionAttribute);
var fi = enumType.GetField(enumValue.ToString());
var descAttrs = fi.GetCustomAttributes(descType, false);

// concatenate multiple descriptions
var desc = string.Empty;
foreach (EnumDescriptionAttribute descAttr in descAttrs)
desc += (desc.Length == 0)
? descAttr.Description
: ", " + descAttr.Description;

if (desc == string.Empty)
desc = enumValue.ToString();

return desc;
}

And the enum value's description is easily found through intellisense:

report.Description()

I can also take it a step further by refactoring my code to include a generic extension method that returns all custom attributes from a value's type, and another that joins an array of strings into one comma delimited string.

public static string Description(this Enum e)
{
var attrs = e.CustomAttributes<Enum, EnumDescriptionAttribute>();
var descs = new List<string>(attrs.Count);
attrs.ForEach(a => descs.Add(a.Description));
return descs.Join();
}

public static List<TAttr> CustomAttributes<T, TAttr>(this T obj)
where TAttr : System.Attribute
{
var fi = obj.GetType().GetField(obj.ToString());
var attrs = fi.GetCustomAttributes(typeof(TAttr), false);
return new List<TAttr>((TAttr[])attrs);
}

public static string Join(this List<string> values)
{
return values.Join(", ");
}
public static string Join(this List<string> values, string delimiter)
{
string result = string.Empty;
values.ForEach(v => result += (result.Length == 0) ? v : delimiter + v);
return result;
}

Of course, the custom attributes method still needs to be refactored to support other types.

Useful For More Than Utility Methods

Since extension methods can be used on sealed classes, they could also be used to hide methods from a publicly distributed assembly by putting extension methods in a non-distributed assembly. Of course, you could also accomplish this with a partial class. Sure, there are probably plenty of reasons why this would be a bad idea, but I get hyper over syntax additions, even if they're not really offering anything that you couldn't do before with more mundane code.

There seems to be a lot of controversy over whether extension methods are a good practice and should be part of object oriented programming. Some of the reasons I've seen people use to not use extension methods are that they complicate code discoverability, they will make code reviews more difficult, they don't follow object oriented principles, or even that they contradict best practices published previously by Microsoft. I think Scott Wisniewski of the VB Compiler Team does a great job addressing the benefits of extension methods in his introduction to an excellent series of in depth blog posts, which are also a good read to get a VB.NET perspective on the new feature.

Labels: ,

Saturday, March 31, 2007 2:08:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
betas | c#
Comments are closed.
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Matt Casto
Sign In
All Content © 2008, Matt Casto
Theme based on DasBlog theme 'Business' created by Christoph De Baene (delarou)