Finds the field recursive by name. - CSharp System.Reflection

CSharp examples for System.Reflection:FieldInfo

Description

Finds the field recursive by name.

Demo Code

// Copyright (c) Daniel Dabrowski - rod.blogsome.com.  All rights reserved.
using global::System.Reflection;
using global::System;

public class Main{
        /// <summary>
      /// Finds the field recursive by name.
      /// </summary>
      /// <param name="type">The class type.</param>
      /// <param name="name">The field name.</param>
      /// <returns>FieldInfo or null if there is no field with such name.</returns>
      public static FieldInfo FindField(Type type, string name)
      {//from  w w  w.j  ava  2s. co  m
         if (type == null || type == typeof(object))
         {
            // the full inheritance chain has been walked and we could
            // not find the Field
            return null;
         }

         return type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly) ??
               FindField(type.BaseType, name);
      }
}

Related Tutorials