- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extension Methods in C#
Extension methods are static methods, which are called as if they were instance methods on the extended type. With Extension methods, you can add methods to existing types without even creating a new derived type, recompiling, or modifying the original type.
The following is the extension method we have created.
public static int myExtensionMethod(this string str) { return Int32.Parse(str); }
Let us see an example wherein we have used extension method.
Example
using System; using System.Text; namespace Program { public static class Demo { public static int myExtensionMethod(this string str) { return Int32.Parse(str); } } class Program { static void Main(string[] args) { string str1 = "565"; int n = str1.myExtensionMethod(); Console.WriteLine("Result: {0}", n); Console.ReadLine(); } } }
Output
Result: 565
Advertisements