We started using C# (.NET 3.0) and I wonder how you guys are using extension methods? When do you use them?
Also, I would appreciate if you also list all dark prerequisites for using them.
We started using C# (.NET 3.0) and I wonder how you guys are using extension methods? When do you use them?
Also, I would appreciate if you also list all dark prerequisites for using them.
Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here's a couple of rules to consider when deciding on whether or not to use extension methods:
Extension methods cannot be used to override existing methods
An extension method with the same name and signature as an instance method will not be called
The concept of extension methods cannot be applied to fields, properties or events
Use extension methods sparingly....overuse can be a bad thing!
Times to use extension methods:
For an example of the second point; you might have an extension method on IList<T>
(for example, Sort
) that can be written entirely using the existing IList<T>
members... so why force anybody else to write anything? This is the foundation block of LINQ, and allowed Microsoft to provide much more functionality without breaking anything.
Times to not use extension methods:
I use extension methods when it makes sense. If you control a class and its code, you usually don't need extension methods.
If you don't, an extension method might be useful.
One place I frequently use extension methods is for [Flags] enumerations. When you have a flag-based enumeration, there's a rather large expression that's necessary to determine whether or not an enumeration value has a particular flag set. And so I build the following extension method whenever I build a [Flags] enumeration:
[Flags]
public enum MyEnum
{
FlagA,
FlagB,
// etc.
}
public static class MyEnumExt
{
public static bool HasFlags(this MyEnum item, MyEnum query)
{
return ((item & query) == query);
}
}
That way my code looks like:
MyEnum flags = MyEnum.FlagA;
if(flags.HasFlags(MyEnum.FlagA))
{
// handle FlagA
}
Rather than:
MyEnum flags = MyEnum.FlagA;
if((flags & MyEnum.FlagA) == MyEnum.FlagA)
{
// handle FlagA
}
Also see this question http://stackoverflow.com/questions/474074/overriding-extension-methods/474108#474108