How to add function to an existing type through Extension method feature in C#

Vishal Pathak
Abhima C# Programming
2 min readJan 15, 2022

You may have seen in some programming languages to add methods to an existing types like JavaScript by using “__proto__”. This same can be achieved in C# with much better way, so let’s dive in .

Photo by Wim Arys on Unsplash

Extension method enables you to add methods to existing type without creating a new derived type, recompiling , or otherwise modifying the original type.

Extension methods are static methods, but they are called as if they were instance methods on the extended type. Let’s understand by example 😉.

As you can first we created static class and used static method as well which returns addition of two in variable then we have provided two parameters let’s understand about them below.

this int num1

From the “this int num1” this points to the variable through which this method will be called. And “int” provides the type of the variable through which the method will be called.

Now let’s see how this method will be called through int variable.

As you can see in above code how addNumber method is being called as it is inbuilt method , result variable will have addition of 5 and 20 which is 25.

I hope you understand how to add extension method to existing type in C#. If this article was helpful for you please clap, comment and follow me to help you more.

Bhagavad Gita Verse of the Day

तत्रैकस्थं जगत्कृत्स्नं प्रविभक्तमनेकधा |
अपश्यद्देवदेवस्य शरीरे पाण्डवस्तदा || 13||

tatraika-sthaṁ jagat kṛitsnaṁ pravibhaktam anekadhā
apaśhyad deva-devasya śharīre pāṇḍavas tadā

BG 11.13: There Arjun could see the totality of the entire universe established in one place, in that body of the God of gods.

--

--

Vishal Pathak
Abhima C# Programming

love ❤ coding, solving some industry problems technologies: JavaScript, C#, Angular, PLSQL, Docker Want to learn: Python, Go language, AI, ML and Cloud