Yes you can, that is the only reason we have extention method.I have added a third party dll — here is the command“Install-Package Calculator -Version 1.0.0.1”
That has only one method “Add”
I have added DevideBy10 as extention method.
See this below code.
using System;using Tranform.Try;namespace test{ static class Test { static Calculator calculator = new Calculator(); public static string DevideBy10 (this Calculator calc, int number) { return "= " +(number/10).ToString(); } public static void Main() { Console.WriteLine(calculator.Add(5, 5)); Console.WriteLine(calculator.DevideBy10(50)); Console.Read(); } }}
using System;
using Tranform.Try;
namespace test
{
static class Test
static Calculator calculator = new Calculator();
public static string DevideBy10 (this Calculator calc, int number)
return "= " +(number/10).ToString();
}
public static void Main()
Console.WriteLine(calculator.Add(5, 5));
Console.WriteLine(calculator.DevideBy10(50));
Console.Read();
Extension methods are additional custom methods which were originally not included with the class. It is a mechanism of adding methods into an existing class or structure also without modifying the source code of original type. Below is an example adding a method to the int class:namespace ExtensionMethods {public static class IntExtensions{public static bool IsGreaterThan(this int i, int value){return i > value;}} }
You can always add an Extension Method to a class that you have no control over, whether it was a core .NET class or a referenced dll. Below is an example adding a method to the String class:namespace ExtensionMethods {public static class MyExtensions{public static int WordCount(this String str){return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;}} }Note: Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
By using extension methods on the class.
You cannot get the DLLs code unless you are using Code reflector.Well if dll has only one method and you want to add more methods to it then why not inherit the dll class in your own class and then do whatever you want in your class. If not then extension methods are the best
public static class Extension{ public static void CallBy(this Car obj1) { //You logic here; }}
public static class Extension
public static void CallBy(this Car obj1)
//You logic here;
Extension methods are always staticNow I can use it my program like
static void Main(string[] args){ CrossProjectDemo.Car obj = new Car(); obj.AsParallel(); obj.CallBy();}
static void Main(string[] args)
CrossProjectDemo.Car obj = new Car();
obj.AsParallel();
obj.CallBy();
As simple as that.
There are lot of extension methods in .Net framework. AsParallel() is on of them.
AsParallel()
ParallelEnumerable
Hope this helps you.
Add using ExtensionMethods.Extensions.Basic;to the name space. Then apply the extended method to a precompiled class