0
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?

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.