Monday, June 30, 2014

C# Extension Methods Example

Hi in this post i will show how to create extension methods in c#.

Lets understand with the help of an example.

Example :


1. For creating a extension method we have to create a static class and inside that we have to define a static method which will be used as an extension method.


2. In the above example u can see the extension method reverseString() for data type string.
this extension method will reverse a string and then will return us the output.

3. Code & Output :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string Str = "software";
            Console.WriteLine("Reversed String:{0}", Str.reverseString());
            Console.ReadLine();
        }
    }

    public static class ExtensionForString
    {
        public static string reverseString(this string str)
        {
            char[] cArray = str.ToCharArray();
            string reverse = String.Empty;
            for (int i = cArray.Length - 1; i > -1; i--)
            {
                reverse += cArray[i];
            }
            return reverse;
        }
    }
}