views:

72

answers:

1

I want to be able to call a method that creates an object and sets properties of the object based on the parameters passed into the method. The number of parameters is arbitrary, but the catch is I don't want to use strings. I want to use the actual properties sort of like you do in lambda expressions.

I want to be able to call the method with something that might look like this:

controller.Create<Person>(f=>{f.Name = 'John', f.Age = 30})

or something along those lines where I use the actual property reference (f.Name) instead of a string representation of the property.

Another stipulation is that I don't want any work to be done before the method call. I'm writing this in a library, so I don't want the user to have to do anything except make the call and get back an object with the properties set to the values passed in.

+2  A: 

You can do something like:

controller.Create<Person>(f => { f.Name = 'John'; f.Age = 30; })

The create method signature will be:

public T Create<T>(Action<T> propertySetter) where T : class {
    T value = ...;
    propertySetter(value);
    return value;
}

where T : class is not strictly required here but if T is a value type, the modifications to its properties would be lost.

Mehrdad Afshari
change propertySetter to Func<T,T> and return value; to return propertySetter(value); and it would work for reference types and value types
Rune FS
Rune FS: That way, you would need a return statement in the lambda. I wanted to avoid that.
Mehrdad Afshari
I actually had to take the <T> off of the Create for it to work in my scenario, but it works great.
Brian