Search code examples
c#.netpolymorphismsystem.reflection

Type introspection - get property or fields information


if you do need to get a required information, being a field or properties values / names,

HOW could you do it not by using System.Reflection ?

public class anyClass
{
    public const string UserID  = "usrID",
                        UserName = "usrName";
}

so it happens, as i really wanted to know if it's possible to avoid using reflection,

i have conducted a little research and ..seems to me that, the correct Term for my mission is

Type introspection ( a dediced tag does not exitst here in SO)

Introspection should not be confused with reflection,

which goes a step further and is the ability for a program to manipulate the values,

meta-data, properties and/or functions of an object at runtime.

by using system reflection i could access Fields- values, as in this example code :

    var ac = new anyClass();
    public List<string> anyClassFieldsValuesList()
    {
      // sorry this was the one for the class above
      return typeof(anyClass).GetFields()
                     .Select(f =>f.GetValue(ac).ToString()).ToList<string>();


     // this would do for nested class
     // return typeof(anyClass).GetNestedTypes()
                    .First(t => String.Compare(t.Name, "anyNested", true) == 0)
                    .GetFields()
                    .Select(f => f.GetValue(ac).ToString())
                    .ToList<string>();
    }

Does .net offers us a usage of tools or other approach to get that information in a less expensive way ?


Solution

  • The emphasis on expensive suggests that performance is your main concern. If that is the case, there are libraries out there that exist to remove the overhead of reflection, by caching of metadata and meta-programming. But they are often very specific in their intent.

    For example, FastMember will help with knowing what members exist, and allowing access to their values (without the usual associated overhead of reflection), but: it doesn't help with the GetNestedTypes bit.

    For example, to get all values from a given object, based on what ac actually is:

    // requires FastMember
    var accessor = TypeAccessor.Create(ac.GetType());
    var values = accessor.GetMembers()
            .Select(member => accessor[ac, member.Name]).ToList();