Extension Method :
- This is concept is meant for extending the methods of a class.
- There are two ways to extend a class:
- Inheritance
- Extension Methods
- As you know already in "inheritance", you can extend the features of a class by defining derived class.
- But in this "inheritance" feature, you are creating two classes (base class and derived class).
- But, if you want to add a method to an existing class, that is accessible with the objects of the same class, it is not possible in inheritance". But it is possible using Extension Methods".
- Conclusion : This feature allows you to add one or more new methods to the same class, without changing the definition of that particular class.
- This is more useful, when you want to add more methods to a pre-defined class.
Implementation :
C# Coding on Extension Method :
StringExtension.cs
==================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodsDemo
{
static class StringExtension
{
public static string Reverse(this String str)
{
char[] ch = str.ToCharArray();
Array.Reverse(ch);
string mystr = new String(ch);
return (mystr);
}
}
}
Program.cs
==========
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodsDemo
{
class Program
{
static void Main(string[] args)
{
string s = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(s.Reverse());
Console.Read();
}
}
}
0 Comments