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.

eg: http://blogs.msdn.com/b/wriju/archive/2011/05/04/linq-to-xml-handling-blank-or-no-element-and-attribute.aspx

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#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s