[c#] Using PropertyInfo.GetValue()

I have a class that creates a static array of all properties, using a static constructor. I also have a function -- GetNamesAndTypes() -- that lists the name & type of each property in that array.

Now I want to create another instance-level function -- GetNamesAndTypesAndValues() -- that displays the name & type of each property in the class, as well as that instance's value. How would I do that? Here's the code that I've written so far:

//StaticTest.cs
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;

namespace StaticTest
{
    public class ClassTest
    {
        private string m_A, m_B, m_C;
        private static PropertyInfo[] allClassProperties;

        static ClassTest()
        {
            Type type = typeof(ClassTest);
            allClassProperties = type.GetProperties();

            // Sort properties alphabetically by name 
            // (http://www.csharp-examples.net/reflection-property-names/)
            Array.Sort(allClassProperties, delegate(PropertyInfo p1, PropertyInfo p2)
            {
                return p1.Name.CompareTo(p2.Name);
            });
        }

        public int A
        {
            get { return Convert.ToInt32(m_A); }
            set { m_A = value.ToString(); }
        }

        public string B
        {
            get { return m_B; }
            set { m_B = value; }
        }

        public DateTime C
        {
            get { return DateTime.ParseExact("yyyyMMdd", m_C, 
                                  CultureInfo.InvariantCulture); }
            set { m_C = String.Format("{0:yyyyMMdd}", value); }
        }

        public static void GetNamesAndTypes()
        {
            foreach (PropertyInfo propertyInfo in allClassProperties)
            {
                Console.WriteLine("{0} [type = {1}]", propertyInfo.Name, 
                                           propertyInfo.PropertyType);
            }
        }

        public void GetNamesAndTypesAndValues()
        {
            foreach (PropertyInfo propertyInfo in allClassProperties)
            {
                Console.WriteLine("{0} [type = {1}]", propertyInfo.Name, 
                                             propertyInfo.PropertyType);
            }
        }
    }
}

//Program.cs
using System;
using System.Collections.Generic;
using StaticTest;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("[static] GetNamesAndTypes()");
            ClassTest.GetNamesAndTypes();
            Console.WriteLine("");

            ClassTest classTest = new ClassTest();
            classTest.A = 4;
            classTest.B = @"bacon";
            classTest.C = DateTime.Now;
            Console.WriteLine("[instance] GetNamesAndTypesAndValues()");
            classTest.GetNamesAndTypesAndValues();

            Console.ReadLine();
        }
    }
}

I tried using propertyInfo.GetValue(), but I couldn't get it to work.

This question is related to c# .net reflection

The answer is


In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to reflection

Get properties of a class Get class name of object as string in Swift Set field value with reflection Using isKindOfClass with Swift I want to get the type of a variable at runtime Loading DLLs at runtime in C# How to have Java method return generic list of any type? Java reflection: how to get field value from an object, not knowing its class Dynamically Add C# Properties at Runtime Check if a property exists in a class