user1885158
user1885158

Reputation: 21

Init lazy property with dynamic property

I would like init a lazy property dynamically with reflection.

I loop on my object properties and I want to create a lazy loading of this property like this :

Lazy<propertyInfo.propertyType> = new lazy<propertyInfo.propertyType>(() => methodInfo.invoke)

Lazy doesn't allow this.

Is there a way to do this with reflection ? (maybe activator.createinstance)

Upvotes: 2

Views: 672

Answers (1)

codingadventures
codingadventures

Reputation: 2952

Try this:

Lazy<object> lazyType = new Lazy<object>(() => {
    return Activator.CreateInstance(propertyInfo.propertyType);
});

lazyType.Value;

when u access the Value property the Lazy object will call the Func and then return an instance of your property type.

hope it helps

Upvotes: 1

Related Questions