Monday, 22 September 2008

Fun with Extension Methods

I've recently been brushing up on my c# and .NET skills, and have started to post some blogs on my findings.  To start I have been looking at Extension methods, and how they can be useful in every day coding.

To demonstrate these I have chosen simple conversion methods.  Specifically, converting an integer to Hex, Octal and Binary strings and converting a binary string into an int32 value.  I re-iterate that these are simple, but they demonstrate how quick and easy it is to create extension methods for your existing objects, and to the .NET native types.

Firstly, a few rules.

MSDN states that ;

"Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the 'this' modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive."

So, to start with we will create 2 static classes (in this example the static classes are in the same namespace as the console application).

static class IntExtensions
{
public static string ToHex(this int value)
{
return Convert.ToString(value, 16);
}

public static string ToOctal(this int value)
{
return Convert.ToString(value, 8);
}

public static string ToBinary(this int value)
{
return Convert.ToString(value, 2);
}
}

static class StringExtensions
{
public static int ToInt(this string value)
{
return int.Parse(Convert.ToInt32(value, 2).ToString("X"));
}
}



Lets deal with the IntExtensions class first.  Here I have created 3 extension methods, ToHex() ToOctal() and ToBinary().  These are REALLY simple methods that use the System.Convert static class to convert the int values to strings using ToString() and passing the base as a parameter.  The key thing to note here is the 'this' modifier in the parameter list for the methods.  This tells the compiler that this is an extension method to the specified type (in this case int).



Now, why not just use the System.Convert static class explicitly in the code?  Why not indeed, there is no real reason why you can't.  But I'm sure that you agree that calling;




int value1 = 16;
string asHex = value1.ToHex();



reads a lot better than;



int value1 = 16;
string asHex = System.Convert.ToString(value1, 16);


 



The same principle applies to my StringExtensions class.  Here I have a ToInt() conversion which converts a binary string to an int32 value. 



string value3 = "00000001";
int toInt = value3.ToInt();


Full Code



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Samples.ExtensionMethods
{
class Program
{
static void Main(string[] args)
{
int value1 = 10;
int value2 = 16;
var asHex
= value1.ToHex();

string value3 = "00000001";
string value4 = "00000010";
string value5 = "00000100";
string value6 = "00001000";

Console.WriteLine(
"===================");
Console.WriteLine(
"To Base 2, 8 and 16");
Console.WriteLine(
"===================");
Console.WriteLine(
string.Format("{0} as base 16 = {1}",value1, value1.ToHex()));
Console.WriteLine(
string.Format("{0} as base 16 = {1}",value2, value2.ToHex()));

Console.WriteLine(
string.Format("{0} as base 8 = {1}", value2, value1.ToOctal()));
Console.WriteLine(
string.Format("{0} as base 8 = {1}", value2, value2.ToOctal()));

Console.WriteLine(
string.Format("{0} as base 2 = {1}", value1, value1.ToBinary()));
Console.WriteLine(
string.Format("{0} as base 2 = {1}", value2, value2.ToBinary()));

Console.WriteLine(
"==========================");
Console.WriteLine(
"To int from Binary strings");
Console.WriteLine(
"==========================");
Console.WriteLine(
string.Format("{0} as int = {1}", value3, value3.ToInt()));
Console.WriteLine(
string.Format("{0} as int = {1}", value4, value4.ToInt()));
Console.WriteLine(
string.Format("{0} as int = {1}", value5, value5.ToInt()));
Console.WriteLine(
string.Format("{0} as int = {1}", value6, value6.ToInt()));
}
}

static class IntExtensions
{
public static string ToHex(this int value)
{
return Convert.ToString(value, 16);
}

public static string ToOctal(this int value)
{
return Convert.ToString(value, 8);
}

public static string ToBinary(this int value)
{
return Convert.ToString(value, 2);
}
}

static class StringExtensions
{
public static int ToInt(this string value)
{
return int.Parse(Convert.ToInt32(value, 2).ToString("X"));
}
}

}


Output



image



 



Anyhoo, this is just a an example of using Extension Methods for simple type conversions.  The same principles can be applied to any object.



Have fun!