Monday, August 03, 2009

Extension Methods in C#

C# has a nice feature called Extension Methods - You can extend the APIs of an Interface or Class by Extesnsion class and methods.
Please refer to the following link for details about usage ( )
This feature is purticularly useful for extending functionality of Interfaces/classes which are not instantiated by us (for example DataReader which typically goy by SqlCommand.ExecuteReader() )
Assume we want to introduce a method for retrieving values from DataReader even if the value is null in database (by default it will throw exception if we try to read data which is null in database)
We can write the following Class for that (Stolen shamelessly from this Answer by Tommy Carlier on stackoverflow )

static class DataReaderExtension
public static string GetStringOrNull(this IDataReader reader, int ordinal)
return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
We can use this as follows:
SqlDataReader reader = command.ExectureReader();
string value = reader.GetStringOrNull(0); // this will not break even if value is null
Without Extension methods to achieve this functionality we would have written wrapper class and implement all unnecessary methods also.

No comments: