Create an extension method using a given third-party DLL. Say, I get a dll from a third party and it has only one method. Now, I want to add a new method to it but I can't get the dll's source code. How?
Prasad Raveendran
Select an image from your device to upload
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();
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.