.Net

Extension Methods in C#

In this blog we are going to know what is Extension Methods and how we can create a Extension Methods.

  • An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. We can say that it extends the functionality of an existing type in . NET.  An Extension Method is a static method to the existing static class.
  • If we want to add a extension method to an int we have to create a static class and a static method within that class and pass the argument like (this int vairablename).

Example :

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

namespace ExtensionMethodExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 152;
            string message = num.PrimeNumber();
            Console.WriteLine(message);
            Console.ReadLine();
        }
    }

    public static class ExtensionMethod
    {
        public static string PrimeNumber(this int num)
        {
            int n = num, a = 0;
            for (int i = 1; i <= n; i++)
            {
                if (n % i == 0)
                {
                    a++;
                }
            }
            if (a == 2)
            {
                return "Prime Number";
            }
            else
            {
                return "Not a Prime Number";
            }
        }
    }
}

I have also attached a video link here – https://youtu.be/f9bhlGhHSPc

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Check Also
Close
Back to top button