Wednesday 30 September 2015

Extension method example in c#

This extension methods allow us to add some methods in existing types, these type could be user defined or predefined. I am exploring a simple example to demonstrate predefined types with extension method;


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

namespace ExtensionMethod
{
    class Program{
        static void Main(string[] args)
        {
            string name = "raj kumar";
            Console.WriteLine(name.capitalize());
            Console.Read();
        }
    }
    
    public static  class MyExtensionMethods {
        public static string capitalize(this string value)
        {
            //
            // Uppercase the first letter of each words in the string.
            //
            if (value.Length > 0)
            {
                var result =string.Join(" ",value.Split(' ').Select(o => o.ToCharArray().First().ToString().ToUpper()
                    + o.Substring(1,o.Length -1) )); //+ new string(o.Skip(1).ToArray()) ));
                return result;
            }
            return value;
        }
    }
}
//Output: 

  
 

More on Microsoft site:
http://blogs.msdn.com/b/spike/archive/2010/01/18/how-to-create-a-simple-extension-method-a-simple-example.aspx