Skip to content

Instantly share code, notes, and snippets.

@Jalalx
Created October 1, 2019 11:00
Show Gist options
  • Save Jalalx/c268e50968f9696ad915744c63087172 to your computer and use it in GitHub Desktop.
Save Jalalx/c268e50968f9696ad915744c63087172 to your computer and use it in GitHub Desktop.
using System;
using System.Linq.Expressions;
using System.Text;
namespace ExpressionValueEvaluator
{
class Program
{
static string Name => "Some Value (Direct Property)";
static void Main(string[] args)
{
Organization org = new Organization { Manager = new Person { FullName = "Some Value (Nested Property)" } };
Person p = new Person { FullName = "Some Value (From Object Property))" };
string name = "Some Value (From variable))";
const string constName = "Some Value (From Const Field)";
Print(() => p.FullName);
Print(() => name);
Print(() => org.Manager.FullName);
Print(() => GetSomeName());
Print(() => new MethodContainer().GetSomeName());
Print(() => "Some Value (Const Value)");
Print(() => constName);
Print(() => Name);
/*
FullName: Some Value (From Object Property))
name: Some Value (From variable))
FullName: Some Value (Nested Property)
GetSomeName: Some Value (From Method)
GetSomeName: Some Value (From Method in another class)
Some Value (Const Value)
Some Value (From Const Field)
Name: Some Value (Direct Property)
*/
}
static string GetSomeName()
{
return "Some Value (From Method)";
}
static void Print(Expression<Func<string>> expr)
{
if (expr.Body is MemberExpression)
{
var memberExpr = (expr.Body as MemberExpression);
var value = Expression.Lambda(memberExpr).Compile().DynamicInvoke();
var result = $"{memberExpr.Member.Name}: {value}";
Console.WriteLine(result);
}
else if (expr.Body is MethodCallExpression)
{
var methodCallExpr = (expr.Body as MethodCallExpression);
var value = Expression.Lambda(methodCallExpr).Compile().DynamicInvoke();
var result = $"{methodCallExpr.Method.Name}: {value}";
Console.WriteLine(result);
}
else if (expr.Body is ConstantExpression)
{
var constExpr = (expr.Body as ConstantExpression);
var value = Expression.Lambda(constExpr).Compile().DynamicInvoke();
var result = $"{value}";
Console.WriteLine(result);
}
}
}
public class Person
{
public string FullName { get; set; }
}
public class Organization
{
public Person Manager { get; set; }
}
public class MethodContainer
{
public string GetSomeName()
{
return "Some Value (From Method in another class)";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment