Introduction
Extension methods are a convenient way to add methods to classes that you don't own and so can't modify directly.
Look at the program given below:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//create the object of the class
Person p = new Person() { Name = "Abhimanyu", Age = 22 };
//see the result
Console.WriteLine(p.Name + ", " + p.Age);
Console.ReadKey();
}
}
//class
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}
In the above program, I have a 'Person' class having two properties 'Name' and 'Age' and the same I have created an object of the 'Person' class in main method by the name 'p' and then assigning the property value.
Assume I want to extend the 'Person' class (reason may be anything like don't own class etc.) then what we need to do is to extend the 'Person' class by using a static directive (class or method). Look at the program snap below.
//extension method
static class ExtensionMethod
{
public static string Introduce(this Person person)
{
return string.Format("Hello {0} ", person.Name);
}
}

Join the conversation! Your thoughts help the community grow.