Rushikesh Sane
Rushikesh Sane

Reputation: 55

How to access class properties using .(variable_name) in .net core?

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;

Upvotes: 2

Views: 980

Answers (1)

Pedro Brito
Pedro Brito

Reputation: 263

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);

Upvotes: 3

Related Questions