Property parameter?

  • Thread starter Thread starter Berryl Hesh
  • Start date Start date
B

Berryl Hesh

Is there a way to pass a property around as a parameter without reflection?

My current motivation for this is the code below is testing multiple
properties to see that an exception is thrown if a user tries to set the
string value to an empty value. Ideally I'd like to have one method that
would take a Property as a parameter and test it:

[Test]
public void CompanyName_Error_CannotSetToEmpty() {
var customer = new Customer { ID = "TEST" };
try {
customer.CompanyName = string.Empty;
Assert.Fail("EmptyValueException for CompanyName property should
have been thrown.");
}
catch (EmptyValueException ex) {
_assertPropertyNameIsSetProperly(ex, "CompanyName");
}
}

[Test]
public void PhoneNumber_Error_CannotSetToEmpty() {
var customer = new Customer { ID = "TEST" };
try {
customer.Phone = string.Empty;
Assert.Fail("EmptyValueException for Phone property should have
been thrown.");
}
catch (EmptyValueException ex) {
_assertPropertyNameIsSetProperly(ex, "Phone");
}
}

private static void _assertPropertyNameIsSetProperly(EmptyValueException
ex, string expectedName) {
Assert.That(ex.PropertyName, Is.EqualTo(expectedName));
}
 
Is there a way to pass a property around as a parameter without reflection?

Not really - although you could pass round a delegate or pair of
delegates to get/set the property. That would be quite readable using
anonymous methods or lambda expressions.

Jon
 
can you please show me what that would look like?

Is there a way to pass a property around as a parameter without
reflection?

Not really - although you could pass round a delegate or pair of
delegates to get/set the property. That would be quite readable using
anonymous methods or lambda expressions.

Jon
 

Okay, I'll assume you mean you're using .NET 3.5 and C# 3.0. In which
case you can use lambda expressions:

public void SomeMethod<T>(Func<Customer,T> getter, Action<Customer,T>
setter) {
Customer customer = ...;
// When you need to test the getter:
AssertEquals("", getter(customer)); // Or whatever

// When you need to test the setter
setter(customer, value);
}

Then to call SomeMethod:

SomeMethod(customer => customer.Phone, (customer, value) =>
customer.Phone = value);

Jon
 
Back
Top