Pages

Tuesday, February 01, 2011

C# - Get All Properties From Class Or Type

Have you ever try to get all properties from a Class/Type on the fly? the next snippet demonstrates how to query the class instance and retrieve the properties names and their respective values.

It goes like this...




















This way you have a string returned like "propName1: valueProp1\n" and so on.


Reference:

2 comments:

  1. Muito bem, mas fazia duas alterações:
    - o tipo CustomClass é desnecessário, podes usar directamente Object em vez de um tipo específico (isto dado que estás a fazer tudo por Reflection e o GetType retorna mesmo de object)
    - modifica o método GetMessage para um Extension Method; dessa forma podes em qualquer objecto fazer simplesmente: myObject.GetMessage()

    ReplyDelete
  2. Então ficaria,

    private string GetPropertiesAndValues(this object myObject)
    {
    string str = "My object Properties & Values \n\n";

    var propertyNamesAndValues = myObject.GetType()
    .GetProperties()
    .Where(p => p.GetGetMethod() != null)
    .Select(p => new {
    Name = p.Name,
    Value = p.GetGetMethod().Invoke(myObject, null)
    });

    foreach(var pair in propertyNamesAndValues)
    {
    str = str + pair.Name + ": " + pair.Value + "\n";
    }

    return str;
    }

    Abraço

    ReplyDelete