Brian
Brian

Reputation: 1037

How do I set arbitrary number of properties on generic object?

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.

Upvotes: 1

Views: 559

Answers (1)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421988

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.

Upvotes: 2

Related Questions