New Posts  All Forums:Forum Nav:

Extension Methods in C#

post #1 of 3
Thread Starter 
There is some debate amongst developers as to the usefulness of extension methods. I, for one, use them and find them to be great time savers. If you don't use them or don't know how here is a little primer.

The first thing you will need to do is come up with something that you want to encapsulate into an extension method. For this example I will come use some quick and dirty hashing methods. The goal is to make it easier to hash a string or compare said hash with a known value.

The next thing to do is to create a static class (yes, it has to be static). The name can be anything you like, but I like naming mine by target datatype. I am leaving the namespace out of it but obviously that will need to be set (or not) depending on your usage.
Code:
public static class SystemString
{

}

Now put in your methods
Code:
public static class SystemString
{
        public static string MD5(this string input)
        {
            var enc = new System.Text.ASCIIEncoding();
            var md5 = System.Security.Cryptography.MD5.Create();
            var inputBytes = enc.GetBytes(input);
            var hashBytes = md5.ComputeHash(inputBytes);
            return string.Join("", hashBytes.Select(b => b.ToString("X2")).ToArray());
        }

        public static bool VerifyMD5(this string s, string strHash)
        {
            return (strHash == MD5(s));
        }
}

So what you will notice is that the methods look like any others that you have created in the past, with one tiny little exception. The "this" attribute of the first parameter will define what type of variable the extension method will be available. In this case both are strings. The return type of the method works just like it always does.

Lets see it in action...
Code:
var text = "Overclock.net";
var hash = text.MD5();

Console.WriteLine(hash);
The result is: 3E4CFF6DF78D3F687C124769884E6FA1
Code:
var hash = "3E4CFF6DF78D3F687C124769884E6FA1";
var text = "OVERCLOCK.NET";
var test = text.VerifyMD5(hash);

Console.WriteLine(test.ToString());
The result here is: False

So, these are pretty simple ones, but the idea isn't to put all of your logic into extensions. Just those little bits of code that you find yourself doing over and over.

Does anybody have any "favorite" extensions they want to share?

Here is one of the ones I use often. I mentioned it in another post without remembering it was one of my custom extension methods...
Code:
public static class SystemCollectionsGenericIEnumerable
        {
                public static void Each<T>(this IEnumerable<T> ie, Action<T, int> action)
                {
                        if (ie == null) throw new ArgumentNullException("ie");
                        if (action == null) throw new ArgumentNullException("action");

                        var i = 0;
                        foreach (var e in ie) action(e, i++);
                }
        }

Here it is in action.
Code:
void Main()
{
        var list = new List<string>(){"alpha","beta","gamma","delta","epsilon"};
        
        list.Each((l,i) => DoSomething(l.MD5()));
}
        void DoSomething(string s)
        {
                Console.WriteLine(s);
        }
Result: 2C1743A391305FBF367DF8E4F069F9F9
987BCAB01B929EB2C07877B224215C92
05B048D7242CB7B8B57CFA3B1D65ECEA
63BCABF86A9A991864777C631C5B7617
3CD38AB30E1E7002D239DD1A75A6DFA8


"DoSomething" is usually something much more complex.
Main Rig
(15 items)
 
  
Reply
Main Rig
(15 items)
 
  
Reply
post #2 of 3
Thanks, should be good for newbies smile.gif Would rep you if I could.

One that I keep using is IsNegative:
Code:
public bool isNegative(this int param)
{
    return param < 0
}

It's actually very useful, especially for IndexOf.
post #3 of 3
I've never seen this before, but seems pretty cool. That's exactly the type of thing that most people would put into a helper class.
With your example instead of calling this: var hash = text.MD5();
Using a helper you would call something like this: var hash = helper.MD5(text);

Either way works just fine, but using these extensions looks to be a much cleaner approach.
Next time I need something like this, I will definitely try doing it this way.
Death Star
(21 items)
 
Darksaber
(11 items)
 
 
CPUMotherboardGraphicsRAM
Athlon II x2 245 Asus M3A78 Radeon HD6570 1GB Mushkin Silverline 2GB DDR2  
Hard DriveOptical DriveOSMonitor
OCZ Vertex 2 120GB Samsung Blu-Ray Windows 7 Samsung 46" DLP 
PowerCaseOther
Silverstone Strider Essentials 400W Silverstone Milo ML03B Hauppage WinTV 1250 
  hide details  
Reply
Death Star
(21 items)
 
Darksaber
(11 items)
 
 
CPUMotherboardGraphicsRAM
Athlon II x2 245 Asus M3A78 Radeon HD6570 1GB Mushkin Silverline 2GB DDR2  
Hard DriveOptical DriveOSMonitor
OCZ Vertex 2 120GB Samsung Blu-Ray Windows 7 Samsung 46" DLP 
PowerCaseOther
Silverstone Strider Essentials 400W Silverstone Milo ML03B Hauppage WinTV 1250 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Application Programming