Ber53rker
Ber53rker

Reputation: 1038

Reflection within properties?

Below is my current situation....

public string Zip { get { return this.GetValue<string>("Zip"); } set { this.SetValue("Zip", value); } }

I'd like to make this dynamic using reflection. As in, pass the type and name of the property to a method. I'm not sure how to go about it or if it's even possible. Thank you for the assitance.

Edit: Thanks to KooKiz I've been able to get a step further but still not 100% there.

public string Zip { get { return this.GetValue<string>(); } set { this.SetValue(value); } }

Upvotes: 1

Views: 86

Answers (1)

atoth
atoth

Reputation: 858

You could clarify a bit your question. This is too vague for me.

Are you looking for this?

public object DoSomething(Type type, string propertyName)
{
     var somethingWithProperty = Activator.CreateInstance(type, null);
     foreach (PropertyInfo property in somethingWithProperty.GetType().GetProperties())
     {
        if (property.Name == propertyName)
        {
            return property.GetValue(somethingWithProperty, null);
        }
     }

    throw new ArgumentException(string.Format("No property was found was found with this on [{0}] with propertyname [{1}]", type, propertyName));
}

Or this?

    public object DoSomething(Func<object> propertyStuff)
    {
        return propertyStuff();
    }

Usage:

public void FinallyIDoSomethingWithThatSomething()
{
    // first version
    DoSomething(typeof(StrangeOtherClass), "MyLittleProperty");

    // second version
    DoSomething(() => new StrangeOtherClass().MyLittleProperty);
    DoSomething(() => MyPropertyInMyOwnClass);
}

As code-prettifier shows wrong colors for the properties, I'll provide them:

public string MyPropertyInMyOwnClass { get { return "Yay or nay."; } }

Please note, that the second version is more refactor-friendly: in the first version when you refactor StrangeOtherClass and you rename MyLittleProperty, your code will break in run-time as you can easily forget to rewrite the string parameters of the function. With the other version at least the compiler will provide you with the error.

If you provide more information, I could write more specific answer.

Upvotes: 1

Related Questions