Skip to content

Instantly share code, notes, and snippets.

@mgravell
Last active August 30, 2022 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgravell/ee4b8f59e8e4380c951271f1a55483ca to your computer and use it in GitHub Desktop.
Save mgravell/ee4b8f59e8e4380c951271f1a55483ca to your computer and use it in GitHub Desktop.
using System.Linq.Expressions;
using System.Reflection;
using System;
static class P
{
class Foo
{
public Guid Value => _value;
private readonly Guid _value;
public Foo(Guid value) => _value = value;
}
static void Main()
{
var clone = Expression.Parameter(typeof(Foo), "clone");
var value = Expression.Parameter(typeof(Guid), "value");
var fieldInfo = typeof(Foo).GetField("_value", BindingFlags.NonPublic | BindingFlags.Instance);
// ** what we broadly want - but the Expression API disallows because of init-only
// "Expression must be writeable (Parameter 'left')"
// var body = Expression.Assign(Expression.Field(clone, fieldInfo), value);
// long-winded and inefficient way of doing the same thing
var expression = Expression.Convert(value, typeof(object));
var body = Expression.Call(Expression.Constant(fieldInfo), fieldSetValue, clone, expression);
var action = Expression.Lambda<Action<Foo, Guid>>(body, clone, value).Compile();
var obj = new Foo(Guid.NewGuid());
var newGuid = Guid.NewGuid();
Console.WriteLine($"original: {obj.Value}; pushing {newGuid}");
action(obj, newGuid);
Console.WriteLine($"final: {obj.Value}");
}
static readonly MethodInfo fieldSetValue = typeof(FieldInfo).GetMethod(nameof(FieldInfo.SetValue), new[] { typeof(object), typeof(object) });
}
@neerajsahani-logianalytics

Hi,
The above code is similar except for line #18, where my code is slightly different which is as below:
var fieldInfo = typeof(Guid).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

I am not sure of the purpose to use an array of fieldinfo. This array returns the value in Int32, Int16 & byte[] format & this fails in Expression.Call.

This is where I need help.

@mgravell
Copy link
Author

@neerajsahani-logianalytics "I am not sure of the purpose to use an array of fieldinfo." - well, that's your code, not mine - I don't use an array; I can't say anything about your code without being able to see your code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment