Friday, April 15, 2011

So today I was trying to get the following test to pass:

[TestFixture]

public class When_getting_a_step_property_value

{

[Test]

public void a_value_set_can_be_retreived()

{

// Arrange

var model = new FieldMappingModel { DateFormat = "test" };

// Act

var valueFound = new StepValueService().Get(x => x.DateFormat);

// Assert

Assert.AreEqual(model.DateFormat, valueFound);

}

}

 

Where the StepValueService looked like this:

public class StepValueService

{

public dynamic Get(Expression<Func<dynamic, dynamic>> publicGetter)

{

var memberExpression = (MemberExpression)publicGetter.Body;

var propertyName = memberExpression.Member.Name;

// Doing some funky stuff with reflectoin using the properyName

return null;

}

}

This wouldn't compile failing with the following error:

An expression tree may not contain a dynamic operation

Changing the service to the following fixed it but it was rather slow:

public class StepValueService

{

public dynamic Get(Func&lt;dynamic, dynamic&gt; publicGetter)

{

var propertyName = publicGetter(new DynamicMemberNameExpression());

// Doing some funky stuff with reflection using the properyName

return null;

}

private class DynamicMemberNameExpression : DynamicObject

{

public override bool TryGetMember(GetMemberBinder binder, out object result)

{

result = binder.Name;

return true;

}

}

}

Ended up not using this but might be interesting in the future...