Is it possible to exchange implementations of methods in C#, like method swizzling in Objective-C?
So I could replace an existing implementation (from an outside source, via a dll for example) at runtime with my own (or add another onto it).
I have searched for this, but have found nothing of value.
You could use delegates
to have your code point to whatever method you wish to execute at run time.
public delegate void SampleDelegate(string input);
The above is a function pointer to any method which yields void
and takes a string
as input. You can assign any method to it which has that signature. This can also be done at run time.
A simple tutorial can be also found on MSDN.
EDIT, as per your comment:
public delegate void SampleDelegate(string input);
...
//Method 1
public void InputStringToDB(string input)
{
//Input the string to DB
}
...
//Method 2
public void UploadStringToWeb(string input)
{
//Upload the string to the web.
}
...
//Delegate caller
public void DoSomething(string param1, string param2, SampleDelegate uploadFunction)
{
...
uploadFunction("some string");
}
...
//Method selection: (assumes that this is in the same class as Method1 and Method2.
if(inputToDb)
DoSomething("param1", "param2", this.InputStringToDB);
else
DoSomething("param1", "param2", this.UploadStringToWeb);
You can also use Lambda Expressions: DoSomething("param1", "param2", (str) => {// what ever you need to do here });
Another alternative would be to use the Strategy Design Pattern
. In this case, you declare interfaces and use them to denote the behavior provided.
public interface IPrintable
{
public void Print();
}
public class PrintToConsole : IPrintable
{
public void Print()
{
//Print to console
}
}
public class PrintToPrinter : IPrintable
{
public void Print()
{
//Print to printer
}
}
public void DoSomething(IPrintable printer)
{
...
printer.Print();
}
...
if(printToConsole)
DoSomething(new PrintToConsole());
else
DoSomething(new PrintToPrinter());
The second approach is slightly more rigid than the first, but I think it is also another way to go around achieving what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With