Extension Methods December 21, 2009 at 4:54 pm

Extension methods allow us to extend an existing type without
modifying the original type. This means we can extend an existing
type without

re-compiling. So whats the use of that? We have a project with types
spread amongst DLL’s all over the place. Rather than having to locate
the

correct DLL, we can package our modifications in a single DLL with
extension methods.

Don’t overdo it. Keep the extension methods down to utility
extensions. For instance, I need the ability to count the number of
“Person” in my

“People” class. That’s a neat utility that can be slapped on as an extension.

Here I have created an extesion for Thread that tells me if my thread
object is in a state to make my process “hang” and re-used the MSDN
example

for string to do a word count.

using System;
using System.Threading;
using ConsoleApplication3.ExtensionMethods;

namespace ConsoleApplication3
{
namespace ExtensionMethods
{
public static class MyExtensions
{
///

/// Thread is in a state to keep the Process alive after
main thread dies
///

/// ///
public static bool WillKeepAlive(this Thread t)
{
if (!t.IsBackground && t.ThreadState !=
System.Threading.ThreadState.Stopped)
{
return true;
}
else
return false;
}
public static int WordCount(this String str)
{
return str.Split(new char[] { ‘ ‘, ‘.’, ‘?’ },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(Method);
t.Start();
//t.IsBackground = true;//uncomment me to see how I stop hanging!
string s = “blah blah blah blah blah”;
Console.WriteLine(“Word Count {0}”,s.WordCount());

Console.WriteLine(“Main thread complete. Will I hang?
{0}”, t.WillKeepAlive());
}
static void Method()
{
while (true)
{
Console.WriteLine(“Thread still running”);
Thread.Sleep(500);
}
}
}
}

For more info read the Design Guidelines for extension methods.http://blogs.msdn.com/brada/archive/2009/01/12/framework-design-guidelines-extension-methods.aspx
Note:
Extension methods are only in scope when you explicitly import the
namespace into your source code with a using directive.

Rules for defining an extension method:
To defining and call the extension method
1.Define a static class to contain the extension method.

The class must be visible to client code. For more information about
accessibility rules, see Access Modifiers (C# Programming Guide).
2.Implement the extension method as a static method with at least the
same visibility as the containing class.
3.The first parameter of the method specifies the type that the method
operates on; it must be preceded with the this modifier.
4.In the calling code, add a using directive to specify the namespace
that contains the extension method class.
5.Call the methods as if they were instance methods on the type.

Note that the first parameter is not specified by calling code because
it represents the type on which the operator is being applied, and the
compiler already knows the type of your object. You only have to
provide arguments for parameters 2 through n.

Leave a Reply