Skip to content

Instantly share code, notes, and snippets.

@dealproc
Last active August 29, 2015 14:15
Show Gist options
  • Save dealproc/36affe9bc5f32ff1f080 to your computer and use it in GitHub Desktop.
Save dealproc/36affe9bc5f32ff1f080 to your computer and use it in GitHub Desktop.
Setting a member without the "null reference" spam
using System;
using System.Linq.Expressions;
using System.Reflection;
using Xunit;
namespace ReflectedConstructor {
public static class MemberExpressions {
public static MemberInfo GetMemberInfo(this Expression expression) {
var lambda = (LambdaExpression)expression;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression) {
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
} else
memberExpression = (MemberExpression)lambda.Body;
return memberExpression.Member;
}
}
public static class ClassUtils {
public static void SetMember<TClass, TMember>(this TClass theClass, Expression<Func<TMember>> member, TMember value) where TClass : class {
var memberName = member.GetMemberInfo().Name;
if (value == null) {
throw new ArgumentNullException(memberName.Replace('_', ' ').Trim());
}
var field = theClass.GetType().GetField(memberName, BindingFlags.NonPublic | BindingFlags.Instance);
if (field == null) {
throw new InvalidOperationException("Field does not seem to exist.");
}
field.SetValue(theClass, value);
}
}
interface IAmNotImplemented { }
interface IFirstImplementation { }
class AmNotImplemented : IAmNotImplemented { }
class FirstImplementation : IFirstImplementation { }
class UsingImplementation {
readonly IAmNotImplemented _notImplemented;
readonly IFirstImplementation _firstImplementation;
public UsingImplementation(IAmNotImplemented notImplemented, IFirstImplementation firstImplementation) {
this.SetMember(() => _notImplemented, notImplemented);
this.SetMember(() => _firstImplementation, firstImplementation);
}
}
public class TestClass {
[Fact]
public void TheTest() {
var something = new UsingImplementation(new AmNotImplemented(), new FirstImplementation());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment