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

0 0 vote
Article Rating

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x