Search This Blog

Wednesday 24 February 2016

Extension method in C#

Explanation
  1. Extension method must be defined in a non-generic static class.
  2. Extension method must be static.
  3. Extension method first parameter must be start with "this" keyword.
  4. Only one "this" keyword place in Extension method parameter list.
Complete Code

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


namespace ExtensionMethods
{
    class InstanceClass
    {
        public static bool IsNumeric(string value)
        {
            float output;

            return float.TryParse(value, out output); ;
        }

        public static string CamelCaseLetter(string value)
        {
            StringBuilder sb = new StringBuilder();

            if (value.Length > 0)
            {
                string[] strSplit = value.Split(' ');

                foreach (var str in strSplit)
                {
                    char[] charArray = str.ToCharArray();

                    charArray[0] = char.ToUpper(charArray[0]);

                    sb.Append(new string(charArray) + " ");
                }

                return sb.ToString().TrimEnd(' ');
            }
            return value;
        }
    }

    static class StaticClass
    {
        public static bool IsNumeric(this string value)
        {
            float output;

            return float.TryParse(value, out output); ;
        }

        public static string CamelCaseLetter(this string value)
        {
            StringBuilder sb = new StringBuilder();

            if (value.Length > 0)
            {
                string[] strSplit = value.Split(' ');

                foreach (var str in strSplit)
                {
                    char[] charArray = str.ToCharArray();

                    charArray[0] = char.ToUpper(charArray[0]);

                    sb.Append(new string(charArray) + " ");
                }

                return sb.ToString().TrimEnd(' ');
            }
            return value;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string strValue = "hello world";
//Calling Instance Method
            Console.WriteLine(InstanceClass.IsNumeric(strValue));

//Calling Extension Method
            Console.WriteLine(strValue.IsNumeric());

//Calling Instance Method
            Console.WriteLine(InstanceClass.CamelCaseLetter(strValue));

//Calling Extension Method
            Console.WriteLine(strValue.CamelCaseLetter());

            Console.ReadKey();
        }
    }
}


OUTPUT


Note:-

There is no big difference between instance method and extension method. Only “this” keyword of method parameter differentiating with the instance and extension method and the rest of the code as same.

Focus on highlighted code.

How to Call?

Instance method = ClassName.MethodName(value)

Extension method = value.MethodName()

No comments:

Post a Comment