gnome
gnome

Reputation: 1133

C# Reflection with nested property

Trying to set the value of a nested property two levels down using reflection but am getting an object does not not the target object error. The typed obj would look like this: project.EnvironmentalAessment.SomeDocument.Review

var _review = new Review() { .... };
var docProp = project.EnvironmentalAssessment.GetType().GetProperty(techStudy.DocumentProperty);
    var docType = docProp.PropertyType;
    var reviewProp = docType.GetProperty("Review");
    var reviewType = reviewProp.GetType();

project.EnvironmentalAssessment
        .GetType()
        .GetProperty(techStudy.DocumentProperty)
        .PropertyType
        .GetProperty("Review")
        .SetValue(reviewProp, _review, null);

Any insight would be greatly appreciated. Thanks!

Upvotes: 0

Views: 198

Answers (2)

Roberto Hernandez
Roberto Hernandez

Reputation: 2427

You could also use dynamic typing to solve this problem, which would make it easier. I do not know if it would be more efficient in terms of performance than using reflection.

dynamic project = ...;
var review = new Review() { .... };
project.EnvironmentalAessment.SomeDocument.Review = review;

Upvotes: 1

Vyacheslav Volkov
Vyacheslav Volkov

Reputation: 4742

project.EnvironmentalAssessment
            .GetType()
            .GetProperty("SomeDocument")
            .PropertyType
            .GetProperty("Review")
            .SetValue(project.EnvironmentalAssessment.SomeDocument, _review, null);

Or if you do not know the name of the document property:

var docProp = project.EnvironmentalAssessment
            .GetType()
            .GetProperty(techStudy.DocumentProperty);

 docProp.PropertyType.GetProperty("Review")
            .SetValue(docProp.GetValue(project.EnvironmentalAssessment), _review, null);

Upvotes: 1

Related Questions