c# get field by name code example

Example 1: c# get class name by type

typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name

Example 2: 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 3: to string c# fields

public override String ToString()
    {
     	Type objType = this.GetType();
     	PropertyInfo[] propertyInfoList = objType.GetProperties();
     	StringBuilder result = new StringBuilder();
     	foreach (PropertyInfo propertyInfo in propertyInfoList)
      	   result.AppendFormat("{0}:{1},", propertyInfo.Name, propertyInfo.GetValue(this));
          
     	 return "{" + result.ToString() + "}";
     }