Extension methods

Extension methods are used to enhance the functionality of a class whose source code is not available.

In the following example, the class Money’s functionality is extended using an extension method AddToAmount.

The first argument to extension method is the class object whose functionality we want to extend and the second argument is the decimal value.

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


namespace ConsoleApplication6
{
    public class Money
    {
        private decimal amount;

        public decimal Amount
        {
            get
            {
                return amount;
            }

            set
            {
                amount = value;
            }
        }

        public override string ToString()
        {
            return "Rs." + amount.ToString();
        }

    }


public static class MoneyExtension
    {
        public static void AddToAmount(this Money money, decimal amountToAdd)
        {
            money.Amount += amountToAdd;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            Money m = new Money();
            m.Amount = 1000;
            MoneyExtension.AddToAmount(m, 500);
            m.AddToAmount(500);
            Console.WriteLine(m.Amount);
        }        
        
        
    }
}

 

Add a Comment

Your email address will not be published. Required fields are marked *