Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an object property with a string variable that has the name of that property?

Tags:

c#

How do I do this in C#?

using System;

namespace TestProperties28373
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer { FirstName = "Jim", LastName = "Smith", Age = 34};

            Console.WriteLine(customer.FirstName);

            string propertyName = "FirstName";
            Console.WriteLine(customer.&&propertyName); //PSEUDO-CODE

            Console.ReadLine();

        }
    }

    class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
}
like image 514
Edward Tanguay Avatar asked May 28 '09 07:05

Edward Tanguay


2 Answers

Use reflection :

using System.Reflection;

...

PropertyInfo prop = typeof(Customer).GetProperty(propertyName);
object value = prop.GetValue(customer, null);
like image 148
Thomas Levesque Avatar answered Nov 15 '22 19:11

Thomas Levesque


Use System.Reflection and PropertyInfo

like image 25
Russ Cam Avatar answered Nov 15 '22 19:11

Russ Cam