Simple Extension Method Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace extmethods
{
//This class Must be Public.
// even sealed classes can extends by extension methods
public sealed class human
{
public void eat()
{
Console.WriteLine("Eat Food");
}
}
///
/// This is my human Extensions class.This class must be static.
///
public static class humanextension
{
///
public static void eatpkfood(this human h)
{
Console.WriteLine("Eat Pak Food");
}
class Program
{
static void Main(string[] args)
{
human extmethod = new human();
/// The following line used the "eatpkfood" extension method.You can see that object of human class acesses the method of humanextension class.
//This line invokes the "eatpkfood" method of humanextension class.
humanextension.eatpkfood(extmethod);
Console.Read();
}
}
}
OUTPUT:
Eat Pak Food
Eat Pak Food