Property parameter?

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));
}
 
J

Jon Skeet [C# MVP]

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
 
B

Berryl Hesh

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
 
J

Jon Skeet [C# MVP]


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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top