I’m working on a method that accepts an expression tree as a parameter, along with a type (or instance) of a class.
The basic idea is that this method will add certain things to a collection that will be used for validation.
public interface ITestInterface { //Specify stuff here. } private static void DoSomething<T>(Expression<Func<T, object>> expression, params IMyInterface[] rule) { // Stuff is done here. }
The method is called as follows:
class TestClass { public int MyProperty { get; set; } } class OtherTestClass : ITestInterface { // Blah Blah Blah. } static void Main(string[] args) { DoSomething<TestClass>(t => t.MyProperty, new OtherTestClass()); }
I’m doing it this way because I’d like for the property names that are passed in to be strong typed.
A couple of things I’m struggling with..
- Within DoSomething, I’d like to get a
PropertyInfotype (from the body passed in) of T and add it to a collection along with rule[]. Currently, I’m thinking about using expression.Body and removing [propertyname] from "Convert.([propertyname])" and using reflection to get what I need. This seems cumbersome and wrong. Is there a better way? - Is this a specific pattern I’m using?
- Lastly, any suggestions or clarifications as to my misunderstanding of what I’m doing are appreciated and / or resources or good info on C# expression trees are appreciated as well.
Thanks!
Ian
Edit:
An example of what expression.Body.ToString() returns within the DoSomething method is a string that contains "Convert(t.MyProperty)" if called from the example above.
I do need it to be strongly typed, so it will not compile if I change a property name.
Thanks for the suggestions!
Collecting PropertyInfo objects from Expression.Body seems similar to my solution to another question.