Monthly Archives: March 2012

Extention Method with Example

Extension methods enable you to “add” methods to existing types without creating a new derived type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.


Handling blank or no Element and Attribute
public static class MyExtension
//This method is to handle if element is missing
public static string ElementValueNull(this XElement element)
if (element != null)
return element.Value;

return “”;

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method.

Leave a comment

Filed under C#