Saturday, October 18, 2008

Extension Methods in C#

There are some new features in C# 3 which are introduced to make LINQ possible.
One of them are extension methods which I wanted to try out. Extension methods are static methods which can be applied to any object type which is specified as "special parameter". For example if you want to extend the type string with the method "Greet" you write something like this:
public static void Greet(this String s)
{
Console.WriteLine("Hello " + s);
}


Then you can call it like:
string name = "Tom";
name.Greet();


This will produce the following on the console: "Hello Tom"

I played a bit with this extension mehtods and came up with the following extensions for object which I believe can be helpful.
Assume the following object:
Customer testCustomer = new Customer() { Name = "John", Age = 35, LastName = "Smith" };


PrintConsole() -> prints the string representation of an object to the console
Code:
testCustomer.PrintConsole();

Produces:
"ExtensionMethodTest.Customer"

PrintMessageBox() -> shows the string representation of an object in a message box
Code:
testCustomer.PrintMessageBox();

Produces:


PrintPropertiesConsole() -> Prints all public non inherited properties and their values of the object to the console
Code:
testCustomer.PrintPropertiesConsole();

Produces:
Properties of 'ExtensionMethodTest.Customer'
Name: John
LastName: Smith
Age: 35

PrintPropertiesMessageBox() -> Shows all public non inherited properties and their values of the object in a message box
Code:
testCustomer.PrintPropertiesMessageBox();

Produces:

string ToXml() -> Serializes the object to XML and returns the XML string
Code:
testCustomer.ToXml();

Produces:

John
Smith
35



ToXml(Stream stream) -> Serializes the object to XML and writes it to the stream
Code:
testCustomer.ToXml(myStream);


ToXml(string fileName) -> Serializes the object to XML and writes the XML string to the file specified.
Code:
testCustomer.ToXml("c://test.xml);

If you are interested in my project you can download it from here.
Or you can simply download the Extensions.dll from here and import it into your project.

All extension methods are in the namespace System. I know that this is not the way how to do it but so you don't have to add a using directive because System is by default present.

1 comment: