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
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.
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.
Why not use
typeof
as with non-generic type? OrOType
can be assigned at runtime.