Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exchange implementations for C# methods

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.

like image 436
vrwim Avatar asked Sep 13 '25 10:09

vrwim


1 Answers

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.

like image 170
npinti Avatar answered Sep 16 '25 01:09

npinti