Using typeof for a generic object C#

138 views Asked by At

How do I get a list of properties for a generic object?

For Example:

object OType; 
OType = List<Category>; 
foreach (System.Reflection.PropertyInfo prop in typeof(OType).GetProperties())
{
    Response.Write(prop.Name + "<BR>")
} 

Thanks

3

There are 3 answers

1
cyberj0g On

Why not use typeof as with non-generic type? Or OType can be assigned at runtime.

Type OType = typeof(List<Category>); 
foreach (System.Reflection.PropertyInfo prop in OType.GetProperties())
{
    Response.Write(prop.Name + "<BR>")
} 
0
gyosifov On

If I understand correctly the example is a simplification of your case.

If that is the case consider using generics.

public void WriteProps<T>()
{
    foreach (System.Reflection.PropertyInfo prop in typeof(T).GetProperties())
    {
        Response.Write(prop.Name + "<BR>")
    } 
}

...

WriteProps<List<Category>>();

Side note:

In your example you are showing type List<Category>. The GetProperties() will get you the properties of List. If you want the Category properties check this SO question.

0
Luaan On

It sounds like what you actually want to do is get properties of a runtime object, without knowing its exact type at compile-time.

Instead of using typeof (which is a compile-time constant, basically), use GetType:

void PrintOutProperties(object OType)
{
  foreach (System.Reflection.PropertyInfo prop in OType.GetType().GetProperties())
  {
      Response.Write(prop.Name + "<BR>")
  } 
}

Of course, this only works if OType is not null - make sure to include any necessary checks etc.