Extension methods in C#

Extension methods is a parametric type it's always used on a static class. The first variable define in this methods is always "this" keywords.
  • 2418

Introduction

Extension methods is a parametric type It's always used on a static class. The first variable define in this methods is always "this" keywords. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types. Extension Methods you can actually extend the String class to support this directly. You do it by defining a static class with a set of static methods that will be your library of extension methods. Extension methods allow existing classes to be extended without relying on inheritance or having to change the class source code. This means that if you want to add some methods into the existing String class you can do it quite easily.

Example

  • First add a class in your application

 using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ext_method
{
  static class Tom
    {
      public static int sum(this int a, int b)
      {
          int c = a + b;
          return c;
      }
      public static int sub(this int a, int b)
      {
          int c = a - b;
          return c;
      }
      public static int mul(this int a, int b)
      {
          int c = a * b;
          return c;
      }
      public static int div(this int a, int b)
      {
          int c = a / b;
          return c;
      }
  }
}

  • Second write a code on page lode_event.

Code


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Ext_method
{
    public partial class Form1 : Form
    {
        public Form1()

        {
            InitializeComponent();
        }
            int
 a = 10, b = 5;
            private
 void Form1_Load(object sender, EventArgs e)        {
            int c = b.sum(a);
            int c1 = b.sub(a);
            int c2 = b.mul(a);
            int c3 = b.div(a);
            textBox1.Text = c.ToString();
            textBox2.Text = c1.ToString();
            textBox3.Text = c2.ToString();
            textBox4.Text = c3.ToString();
        }
    }
}

Output

output.gif
 

Summary

It is a simple example of extension methods in this article we have see we know need to create the object of class. we used the of class on another place help of parameters but no need to create the object of class.

© 2020 DotNetHeaven. All rights reserved.