views:

214

answers:

3

Is it somehow possible to send a function to another function for it to run. For instance...I want to have an attribute on a field where I can specify a method that will be sent to another method where the method passed in will be run.

Not sure if that makes any sense but here's a small example.

[ValidateIf(x=>x.test())]
public string test { get; set; }

Update: Basically I want to use DataAnnotations for validation but sometimes depending on the system settings a field may not be mandatory...Do you have any suggestions on the direction I should head?

+2  A: 

Unfortunately you can't use delegates as properties for attributes. You'd have to specify the method name and then create the delegate using reflection at execution time - which obviously isn't ideal in terms of finding typos at compile time.

It might be possible in IL (specifying a MethodInfo using an equivalent to typeof) but C# doesn't expose any way of doing this :( Maybe one day we'll get the infoof operator... quite how it would be exposed, I'm not sure. (It would be good to keep the delegate type information in the attribute.)

Jon Skeet
Bassically I want to use DataAnnotations for validation but sometimes depending on the system settings a field may be not mandatory...Do you have any suggestions on the direction I should head?
Schotime
A: 

I don't know if this will meet your specific goal, but in general if you are looking to add data annotations to your language, I recomend you look at Spec#. This is an extension of the C# language that allows you to add data contracts to your program and appears to accomplish the goal you're looking for.

http://research.microsoft.com/en-us/projects/specsharp/

JaredPar
A: 

If you're looking to add validation to your domain objects, you could take a look at NHibernate Validator.

http://nhforge.org/wikis/validator/nhibernate-validator-1-0-0-documentation.aspx

Blake Pettersson