-1

Possible Duplicate:
How to set object property through Reflection

If I have the following program:

public class MyClass
{
    public int MyIntProp {
        get;
        set;
    }
    public string MyStringProp {
        get;
        set;
    }
}

public class MyMainClass
{
    private const string PropertyName = "MyIntProp";
    private MyClass _myClass;

    public MyMainClass()
    {
        _myClass = new MyClass();
        // _myClass.PropertyName = 5;
    }
}

What I want to do is be able to assign a value of 5 to the MyIntProp property. Is it possible to do this using a string name? I though I saw something like this done before using LINQ, but I can't seem to remember the syntax or where I found it.

Community
  • 1
  • 1
Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • You probably don't want to do this. In all likelihood there is a better approach to solving your problem. Reflection is a sledgehammer; don't use it to swat a fly. – Servy Oct 08 '12 at 17:14
  • Here's something similar with LINQ (possibly what you were referring to), for reference: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx – Tim S. Oct 08 '12 at 17:15
  • I agree with @Servy. From your example at least, you should definitely just do `_myClass.MyIntProp = 5;`. – Tim S. Oct 08 '12 at 17:16

1 Answers1

3

You can use Reflection with GetProperty method:

 typeof(MyClass).GetProperty(PropertyName).SetValue(_myClass, 5);
cuongle
  • 74,024
  • 28
  • 151
  • 206
  • The only issue with using reflection is, doesn't the property name change if using automatic getter and setters? I want to say it appends `BackingField` or something like that to the name? – Icemanind Oct 08 '12 at 17:15
  • @icemanind But you're not trying to access the backing field directly, you're just trying to access the property. Take a look at the method; it's `GetProperty`. It's specifically designed to *get* a *property*. – Servy Oct 08 '12 at 17:17
  • @icemanind: well, with the property name changes automatically, I guess to need to have mechanism to to get proper name, could you revise question for more understanding? – cuongle Oct 08 '12 at 17:18
  • @CuongLe: No, its okay. Servy is right and your solution will work because I am trying to get the property and not the backing field :) – Icemanind Oct 08 '12 at 17:21
  • I was looking at [this Stackoverflow Question](http://stackoverflow.com/questions/2675975/reflection-get-fieldinfo-from-propertyinfo) and I saw that the accepted answer was appending `k__BackingField` to the property name. I missed the part where he was asking for the name of the private backing field. – Icemanind Oct 08 '12 at 17:24