Saturday, October 5, 2013

Generics Use Extension Methods

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

namespace Demos
{
    //For creating a static method class shoud be static
    public static class clsUserExtenstionMethod
    {
        //the first parameter type will be associated with "this" keyword
        //Ex:this string s
        //For string object it will get the intellisence
        public static int MyWordCount(this string s)
        {
            return s.Split(' ').Count();
        }

        //
        public static int CalcBonus(this Employee e, int rate)
        {
            return e.Salary * rate / 100;
        }
    }

    class TestUserExtentionMethod
    {

        static void Main()
        {
            CallingExtentionMethod();
            CalCulatingBonus();
        }


        public static void CallingExtentionMethod()
        {
            string msg = "test";
            int x = msg.MyWordCount();
        }      

        private static void CalCulatingBonus()
        {
            foreach (Employee emp in EmployeeList())
            {
                //Calling the User Custom Method
                Console.WriteLine("Bonus {0}", emp.CalcBonus(30));
            }
        }
       
        private static List<Employee> EmployeeList()
        {
            List<Employee> empList = new List<Employee> { new Employee { EmpNo = 1013, EmpName = "Umakar", Dept = "Student", Salary = 15000 },
                                                          new Employee { EmpNo = 1010, EmpName = "Venu", Dept = "HR", Salary = 12000 } };
            return empList;
        }
    }



    public class Employee
    {
        //Step 1
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
        public string Dept { get; set; }
        public int Salary { get; set; }
    }

}


No comments: