Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
This topic is give you a very example source code about class extension!
You have one library write from another developer, and you want to add new method into this dll class, so how do we do it?
Ex: I have two solution
One is CalculatorLibrary (dll class) and another is ClassExtensionExample (Main winform application)
- The CalculatorLibrary dll have one class Calculator with two methods: Plus and Sub
On main application side, we'll create a new multiply method extension to CalculatorLibrary:
Form1.cs (ClassExtensionsExample solution)
NOTE: you must use static class and use this pointer here to description about this extension class is extension for Calculator DLL
After you define it, when you use it, you'll see same image:
You will see the Multiply extension method appear.
You can download full source code here for details view
If you have any questions or feedback, leave your comment we can discuss about it!
Regards!
Zidane
This topic is give you a very example source code about class extension!
You have one library write from another developer, and you want to add new method into this dll class, so how do we do it?
Ex: I have two solution
One is CalculatorLibrary (dll class) and another is ClassExtensionExample (Main winform application)
- The CalculatorLibrary dll have one class Calculator with two methods: Plus and Sub
Calculator.cs (CalculatorLibrary solution)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatorLibrary
{
public class Calculator
{
public int Plus(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
}
On main application side, we'll create a new multiply method extension to CalculatorLibrary:
Form1.cs (ClassExtensionsExample solution)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassExtensionExample
{
public static class CalculatorExtensions
{
public static long Multiply(this CalculatorLibrary.Calculator calc,
int x, int y)
{
return x * y;
}
}
}
NOTE: you must use static class and use this pointer here to description about this extension class is extension for Calculator DLL
After you define it, when you use it, you'll see same image:
You will see the Multiply extension method appear.
You can download full source code here for details view
If you have any questions or feedback, leave your comment we can discuss about it!
Regards!
Zidane
0 comments:
Post a Comment