merp
merp

Reputation: 282

Dynamically Access Properties by Type

I'm trying to access a property that is the same type of which is passed into a generic.

Look at the code:

class CustomClass
{
    CustomProperty property {get; set;}
}

class CustomProperty
{
}

Main
{
        // Create a new instance of my custom class
        CustomClass myClass = new CustomClass();

        // Create a new instance of another class that is the same type as myClass.property
        CustomProperty myProp = new CustomProperty();

        // Call the generic method 
        DynamicallyAccessPropertyOnObject<CustomProperty>(myProp, myClass);
}


private void DynamicallyAccessPropertyOnObject<T>(this T propertyToAccess, CustomClass class)
{
    // I want to access the property (In class) that is the same type of that which is passed in the generic (typeof(propertyToAccess))

    // TODO: I need help accessing the correct property based on the type passed in
}

If you can't see from the code. Basically I want to be able to pass in a something into a generic and then access the property on a class that is of the same type as the thing that was passed in.

Is there a good way to do this? If you need clarification let me know...

Upvotes: 0

Views: 79

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101680

You can use Reflection, and LINQ:

private static void DynamicallyAccessPropertyOnObject<T>()
{
    var customClass = typeof(CustomClass);
    var property = customClass
                  .GetProperties()
                  .FirstOrDefault(x => x.PropertyType == typeof(T));

}

If you are doing this for CustomClass only, you can remove both parameters.Then you can call it:

DynamicallyAccessPropertyOnObject<CustomProperty>();

If you want to generalize it, use two generic arguments:

private static void DynamicallyAccessPropertyOnObject<T, K>(K targetObj)
{
    var targetType = targetObj.GetType();

    var property = targetType
                  .GetProperties()
                  .FirstOrDefault(x => x.PropertyType == typeof(T));

    if(property != null) 
    {
       var value = (T)property.GetValue(targetObj);
    }
}

Then call it:

DynamicallyAccessPropertyOnObject<CustomProperty,CustomClass>(myClass);

Upvotes: 5

Lee
Lee

Reputation: 144106

If there's only one such property you can do:

var prop = typeof(CustomClass).GetProperties().First(p => p.PropertyType == typeof(T));
object value  = prop.GetValue(@class, null);

you can set the value with SetValue:

object valueToSet = ...
prop.SetValue(@class, valueToSet);

Upvotes: 1

Related Questions