2

I have a class as follows -

public class Student
{
    string name {get; set;}
    int age {get; set;}
}

I can access properties by -

Student s = new Student();
var age = s.age;

But what if I want to access properties by doing something like this -

Student s = new Student();
string property = "age";
var value = s.property

And this should return age. The property I want to access is decided at runtime.

Also, I would be interested in knowing the reverse assignment. That is, instead of -

s.age = 25;

Something like

string property = "age";
s.property = 35;

1 Answer 1

3

I don't know the reason for you to do that. But you can achieve that by using Reflection. It is very valuable for certain scenarios, not so valuable for others, in this case is not necessary.

        Student s = new Student();
        string property = "age";
        var age = s.GetType().GetProperty(property);
        age.SetValue(s,25);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is not exactly the use case. The question was formed only to get the solution. Quick question - If I want to do the reverse assignment, that is, s.age = 25; s.GetType().GetRuntimeProperties().First(x=>x.Name== property) = 25; doesn't work. Do you know solution for this too?

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.