curious
curious

Reputation: 117

Convert Func delegate to a string

Is there any way to convert an existing Func delegate to a string like that:

Func<int, int> func = (i) => i*2;
string str = someMethod(func); // returns "Func<int, int> func = (i) => i*2"

or at least smth close to it

Upvotes: 10

Views: 6167

Answers (1)

user1618054
user1618054

Reputation:

I found a similar question here. It more or less boils down to:

By @TheCloudlessSky,

Expression<Func<Product, bool>> exp = (x) => (x.Id > 5 && x.Warranty != false);

string expBody = ((LambdaExpression)exp).Body.ToString(); 
// Gives: ((x.Id > 5) AndAlso (x.Warranty != False))

var paramName = exp.Parameters[0].Name;
var paramTypeName = exp.Parameters[0].Type.Name;

// You could easily add "OrElse" and others...
expBody = expBody.Replace(paramName + ".", paramTypeName + ".")
             .Replace("AndAlso", "&&");


Console.WriteLine(expBody);
// Output: ((Product.Id > 5) && (Product.Warranty != False))

It doesn't return the Func<int, int> func = (i) => part like in your question, but it does get the underlying expression!

Upvotes: 2

Related Questions