Saeid
Saeid

Reputation: 693

How to get and set property of an object which might be property of another object?

I have an object called myConstraint which might have a property called Parameter.

The Parameter is an object that has the Name property which is of type string.

I want to check Constraint and if it has the property Parameter get the string Parameter.Name and if it is equal to "Length" Set the value of Constraint.Parameter to myLengthParameter.

I cannot use Constraint.Parameter since the compiler does not know if the object has property Parameter until program is run. I tried to use reflection but I could not figure this out. I would appreciate your help.

Upvotes: 0

Views: 119

Answers (2)

Alberto Monteiro
Alberto Monteiro

Reputation: 6239

Yeah, you can use reflection to do that.

Since constraint variable can have any value, so you can do something like that.

var property = constraint.GetType().GetProperty("Parameter"); 

if (property != null)
{
    var parameter = property.GetValue(constraint);
    if (parameter != null)
    {
        var parameterName = parameter.GetType().GetProperty("Name").GetValue(parameter).ToString();
        if (parameterName == "Length")
        {
            property.SetValue(constraint, myLengthParameter);
        }
    }        
}

Upvotes: 1

Yong Xiang Low
Yong Xiang Low

Reputation: 36

Check the instance type using is, then cast the object to the Constraint type. (refer to J3soon's comment)

if (myConstraint is Constraint)
{
   // cast and perform your operations here
}

Upvotes: 1

Related Questions