Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created January 6, 2013 14:50
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save riyadparvez/4467678 to your computer and use it in GitHub Desktop.
Save riyadparvez/4467678 to your computer and use it in GitHub Desktop.
Reflection utilities for C#. Get all fields, constructors, methods and properties
/// <summary>
/// Utilties for reflection
/// </summary>
public static class ReflectionUtils
{
/// <summary>
/// Get all the fields of a class
/// </summary>
/// <param name="type">Type object of that class</param>
/// <returns></returns>
public static IEnumerable<FieldInfo> GetAllFields(this Type type)
{
if (type == null)
{
return Enumerable.Empty<FieldInfo>();
}
BindingFlags flags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.DeclaredOnly;
return type.GetFields(flags).Union(GetAllFields(type.BaseType));
}
/// <summary>
/// Get all properties of a class
/// </summary>
/// <param name="type">Type object of that class</param>
/// <returns></returns>
public static IEnumerable<PropertyInfo> GetAllProperties(this Type type)
{
if (type == null)
{
return Enumerable.Empty<PropertyInfo>();
}
BindingFlags flags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.DeclaredOnly;
return type.GetProperties(flags).Union(GetAllProperties(type.BaseType));
}
/// <summary>
/// Get all constructors of a class
/// </summary>
/// <param name="type">Type object of that class</param>
/// <returns></returns>
public static IEnumerable<ConstructorInfo> GetAllConstructors(this Type type)
{
if (type == null)
{
return Enumerable.Empty<ConstructorInfo>();
}
BindingFlags flags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.DeclaredOnly;
return type.GetConstructors(flags);
}
/// <summary>
/// Get all methods of a class
/// </summary>
/// <param name="type">Type object for that class</param>
/// <returns></returns>
public static IEnumerable<MethodInfo> GetAllMethods(this Type type)
{
if (type == null)
{
return Enumerable.Empty<MethodInfo>();
}
BindingFlags flags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.DeclaredOnly;
return type.GetMethods(flags).Union(GetAllMethods(type.BaseType));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment