views:

107

answers:

1

I have written a custom credit card validation attribute that checks CardNumber property is valid for a particular card type (another property in the same class)

[CardValidationBinCheck(this.CardType, 
                        ErrorMessage = "CreditCardNumberDoesNotMatchCardType")]
public string CardNumber
{
 ...
}

This won't compile as studio complains that attribute arguments must be constant, a typeof expression or an array creation expression of an attribute parameter type (?).

Is there anyway I can pass cirvumvent this and pass my this.CardType to the attribute?

Kindness,

Dan

+2  A: 

Unfortunately not. Even if IL allows an attribute value to be a member reference token (e.g. a PropertyInfo effectively) there's no C# operator to get one for you1. You could pass it in as a string literal and then use reflection to get the PropertyInfo though. Ugly and fragile, but probably the closest you'll get.


1 This is a well-known feature request, possibly called the "infoof" operator. There's no sign of it being implemented though.

Jon Skeet
Thanks for the answer, Jon.
Daniel Elliott