Santhosh G
Santhosh G

Reputation: 35

How set value when the property has the getter method using reflection in c#

public class test
{
    public test()
    {
        ting=10;
    }
    private int ting{get;set;}

    public int tring
    {
        get
        {
            return ting;
        }
    }

}

void Main()
{
    var t= new test();

    //Below line giving error
    Console.Write(t.GetType().GetProperty("tring").SetValue(t,20));
}

How to resolve this using reflection?

Upvotes: 0

Views: 452

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

You can't do that, unless you know what is the backing field name. When you do, you can just set the field value, and it will reflect to property value.

Consider the situation when it would be possible and your property wouldn't be backed by a field (like that):

public string tring
{
    get
    {
        return string.format("foo {0} foo", ting);
    }
}

What should be desired output of setting that property?

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503090

Well yes - the property can't be set. It's read-only, presumably deliberately.

If the designer of the class hasn't given you the opportunity of setting the value, you shouldn't be trying to set it. In many cases it would be impossible to do so, as the value may not even be backed by a field (think DateTime.Now) or may be computed some non-reversible way (as per Marcin's answer).

In this particular case if you were really devious you could get hold of the IL implementing tring.get, work out that it's fetching from the ting property, and then call that setter by reflection - but at that point you're going down a very dark path which you're almost certain to regret.

Upvotes: 2

Related Questions