Once a type is defined and compiled into a .NET assembly, its definition is, more or less, final. In order to add new members, update members, or remove members we need to recode and recompile the code base into an updated assembly. Or we could use System.Reflection.Emit namespace to reshape a compiled type dynamically.
Extension methods allow us to extend the functionality of previously compiled types. Using extension methods, we can add functionality to precompiled types while providing the illusion these methods were there all along. When we create extension methods, the existing precompiled assembly is not literally modified. Rather, the type is extended within the current project. If we package extension methods into a custom .NET *.dll, other applications would need to reference this library to make use of the extensions. To this end, extension methods are really just a way to ‘pretend’ a type has new functionality. The real type is not modified in any way.
Why do we need extension methods.
- When we need to inject new functionality into types for which we do not have an existing code base, we can use extension methods.
- When we need to force a type to support a set of members (for the interest of polymorphism) but cannot modify the original type declaration.
- To summarize it is helpful when we need to extend the behavior of a type for a specific functionality but we still want the type to keep behaving as it is, for other parts of application.
Example(s)
public static class ExtensionMethods
{
public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> that,Func<T,bool> predicate)
{
return that.Where(predicate);
}
public static double Distance(this Position currentPosition,Position finalPosition)
{
return System.Math.Sqrt(System.Math.Pow(System.Math.Abs(finalPosition.X - currentPosition.X),2) + System.Math.Pow(System.Math.Abs(finalPosition.X - currentPosition.X),2));
}
public static void Position(this Position that)
{
Console.WriteLine(that.X + " : " + that.Y);
}
}
public class Position
{
public float X { get; set; }
public float Y { get; set; }
}
There are few things to note.
- In C#, extension methods can only be defined within a static class.
- Extension methods need to be static.
- All extension methods are marked as such by using the this keyword as a modifier on the first (and only the first) parameter of the method in question. This parameter represents the data type being extended. Once implemented, extension methods can be called either from the correct instance in memory or statically via the defining static class.
- In a single class we can extend different types.
- Types need not to be present in same namespace. For example we extended IEnumerable<T> and Position classes.
Usage
Using these extended methods:
class Program
{
static void Main(string[] args)
{
//new linq
var students = new[]
{
new student {Name = "anuj", Age = 26},
new student {Name = "gyan", Age = 27}
};
var studentQuery = students.MyWhere(i => i.Age < 27);
foreach(student s in studentQuery)
{
Console.WriteLine(s.Name + ":" + s.Age.ToString());
}
Console.WriteLine("-------------------------------------------------------------");
var position = new Position()
{
X = 2,
Y = 2
};
position.Position();
Console.WriteLine("-------------------------------------------------------------");
int j = 0;
while(true)
{
Console.WriteLine(position.Distance(new Position() {X = j,Y = j}));
Console.ReadLine();
j++;
}
Console.ReadLine();
}
}
public class student
{
private string name;
private int age;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
}
Output
Hope this will be of some help. Please provide your valuable inputs/comments.
Comments
Post a Comment