How to Get a Property Value by Name via Reflection in C#: A Breakdown for Beginners
\n\nImagine a situation: you are writing code where you need to dynamically, on the fly, access a property of an object. The name of this property comes, for example, from a configuration file, a JSON request, or is entered by the user. You cannot hardcode object.PropertyName — you don't know the name in advance. What to do?
Reflection comes to the rescue — a powerful C# mechanism that allows you to examine data types and their members (properties, methods, fields) at runtime. In this article, we will break down the most popular question on Stack Overflow: how to get the value of an object property by a string containing its name. We'll go through real examples, from simple to complex, and look at common pitfalls that beginners encounter.
\n\nWhat is Reflection and Why is it Needed?
\n\nReflection in C# is the ability of a program to "look at itself" and obtain information about its own types. The System.Reflection namespace provides classes like Type, PropertyInfo, MethodInfo, which allow you to:
- \n
- Find out all properties and methods of a class. \n
- Create instances of classes without the
newoperator. \n - Call methods and get/set property values by their string names. \n
Without reflection, you would not be able to, for example, write a universal object mapper (like AutoMapper) or a serializer that works with any data types.
\n\nBasic Example: Getting a Property Value by Name
\n\nLet's say we have a simple class Person:
public class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public string City { get; set; }\n}\n\nWe want to write a method that takes a Person object and a string with the property name (e.g., "Name" or "Age") and returns the value of that property. Here's how to do it using reflection:
using System;\nusing System.Reflection;\n\npublic static object GetPropertyValue(object obj, string propertyName)\n{\n if (obj == null) throw new ArgumentNullException(nameof(obj));\n if (string.IsNullOrEmpty(propertyName)) throw new ArgumentException("Property name cannot be empty", nameof(propertyName));\n\n // Get the type of the object\n Type type = obj.GetType();\n\n // Get information about the property by its name\n PropertyInfo propertyInfo = type.GetProperty(propertyName);\n\n // Check if such a property exists\n if (propertyInfo == null)\n throw new ArgumentException($"Property '{propertyName}' not found in type '{type.Name}'");\n\n // Get the property value\n return propertyInfo.GetValue(obj);\n}\n\nNow let's use our method:
\n\nvar person = new Person { Name = "Anna", Age = 30, City = "Moscow" };\n\nstring name = (string)GetPropertyValue(person, "Name");\nint age = (int)GetPropertyValue(person, "Age");\n\nConsole.WriteLine($"Name: {name}, Age: {age}"); // Output: Name: Anna, Age: 30\n\nIt works! Key points:
\n- \n
obj.GetType()— gets theTypeobject describing the type of our object. \n type.GetProperty("Name")— searches for a public property named "Name". ReturnsPropertyInfoornullif the property is not found. \n propertyInfo.GetValue(obj)— returns the value of this property for the specific instanceobj. \n
Important Nuances and Common Mistakes (What Juniors Don't Tell You)
\n\n1. Case Sensitivity
\nThe GetProperty method is case-sensitive by default. If you specify "name" instead of "Name", the property will not be