Salvia
Salvia

Reputation: 182

How to convert a Delegate to a string of code?

I'm trying to recover the code of a delegate, by converting it to a string, with no success so far ):

Take this piece of code for example:

Delegate del = new Delegate()
del = (MethodInvoker) delegate { MessageBox.Show("hello from delegate") };

I wanna know if there is any operation I can perform on del to retrieve a string representing its C# code.

I Guess what i'm looking for is Serialization, but i'm not sure... I've tried the Delegate.ToString() but it doesnt retur what i want...

Upvotes: 1

Views: 3607

Answers (2)

Polity
Polity

Reputation: 15130

There is no such option.

The delegate can be seen as yet another method. The compiler compiles this down to some MSIL instructions. At that point you lost the original C# source in your assembly and hence, therefore lost the possibility of showing the original C# code itself. (There are some reverse engineering options but those are way to complex).

You can use expressions to setup a representation of what you want and let the runtime boil it down to whatever is required by then (C#, MSIL, SQL etc). example:

Expression<Action> expr = () => MessageBox.Show("test");

Console.WriteLine(expr.ToString()); 
// () => Show("test")

Upvotes: 2

SLaks
SLaks

Reputation: 888047

This is not possible in general.

If you accept an Expression<TDelegate> (an expression tree) instead of an ordinary delegate, you can call ToString() to get a string representation.
However, the compiler can only convert lambda expressions (not blocks) to expression trees.

Upvotes: 4

Related Questions