c# get class property name as string code example

Example 1: C# get object property name

using System.Reflection;  // reflection namespace

// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |
                                              BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos,
        delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
        { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });

// write property names
foreach (PropertyInfo propertyInfo in propertyInfos)
{
  Console.WriteLine(propertyInfo.Name);
}

Example 2: c# get class name as string

// in c# 6.0 you can use nameof(ClassName)
// in older versions you may use typeof(ClassName).Name
// example:
public static class ClassName
{
  public static void PrintName => Console.WriteLine(nameof(ClassName));
}