How to get the value of an object property by its name (string) via reflection in C#?
Hi everyone! I'm new to C# and encountered a task: I have a `Person` class with several properties (`Name`, `Age`, `Email`). I need to write a method that takes an object of this class and a string — the property name, and returns the value of that property. That is, for example, I pass `person` and `"Name"`, and get `"John"`.\n\nI know this can be done via reflection, but I don't understand how to do it correctly. Here's what I tried:\n\n```csharp\npublic class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public string Email { get; set; }\n}\n\nstatic object GetPropertyValue(object obj, string propertyName)\n{\n // How to get the value here? \n // I tried something like obj.GetType().GetProperty(propertyName), but I don't know what to do next
No answers yet.
Log in to leave an answer
Blogs
How to Quickly Learn Python and Land Your First Job: Timelines, Tips, and Real Examples
JavaScript 2025: 7 Trends That Will Change Web Development
Updating a Value in HashMap in Rust: From Beginner to Pro
C++ on LeetCode: How to Solve Problems and Level Up Your Skills