How to Get a Property Value by Name via Reflection in C#: A Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Get a Property Value by Name via Reflection in C#: A Breakdown for Beginners

\n\n

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

\n\n

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\n

What is Reflection and Why is it Needed?

\n\n

Reflection 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\n
    \n
  • Find out all properties and methods of a class.
  • \n
  • Create instances of classes without the new operator.
  • \n
  • Call methods and get/set property values by their string names.
  • \n
\n\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\n

Basic Example: Getting a Property Value by Name

\n\n

Let's say we have a simple class Person:

\n\n
public class Person\n{\n    public string Name { get; set; }\n    public int Age { get; set; }\n    public string City { get; set; }\n}
\n\n

We 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:

\n\n
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\n

Now let's use our method:

\n\n
var 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\n

It works! Key points:

\n
    \n
  • obj.GetType() — gets the Type object describing the type of our object.
  • \n
  • type.GetProperty("Name") — searches for a public property named "Name". Returns PropertyInfo or null if the property is not found.
  • \n
  • propertyInfo.GetValue(obj) — returns the value of this property for the specific instance obj.
  • \n
\n\n

Important Nuances and Common Mistakes (What Juniors Don't Tell You)

\n\n

1. Case Sensitivity

\n

The GetProperty method is case-sensitive by default. If you specify "name" instead of "Name", the property will not be

Blogs

Book Recommendations