Home > database >  How to extract property names from custom class in C#
How to extract property names from custom class in C#

Time:02-18

I am making function for exporting table to .csv file.

I have List where T is custom class.

I need property names of T for columns in .csv file.

How can I extract them to other List ?

CodePudding user response:

You can use reflection:

var propertyNames = typeof(T).GetProperties()
      .Select(p => p.Name));

CodePudding user response:

Your question was a tad hard to understand. However I wrote some example code for you, hopefully it answers your question. As I believe you just needed help with the reflection part of the question.

using System.Reflection;

namespace Example
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var types = Assembly.GetExecutingAssembly().GetTypes();
            foreach (var type in types)
            {
                var props = GetProperties(type);

                foreach (var property in props)
                {
                    Console.WriteLine($"Type: {type.FullName} -> Property: {property.Name}");
                }
            }
        }

        public static PropertyInfo[] GetProperties(Type T)
        {
            return T.GetProperties();
        }
    }

    public class TestClass
    {
        public int Health { get; set; } // Example property
    }
}
  • Related