/// <summary> /// Obtain the backing field for an auto-implemented property. /// </summary> /// <param name="property">An auto-implemented property.</param> /// <param name="bindingFlags">Flags filtering the visibility of the property.</param> /// <returns>The field for an auto-implemented property if it exists.</returns> /// <exception cref="ArgumentNullException"><paramref name="property"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException"><paramref name="bindingFlags"/> is not a valid enumeration.</exception> public static FieldInfo?GetAutoBackingField(this PropertyInfo property, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy) { if (property == null) { throw new ArgumentNullException(nameof(property)); } if (!bindingFlags.IsValid()) { throw new ArgumentException($"The { nameof(BindingFlags) } provided must be a valid enum.", nameof(bindingFlags)); } var backingFieldName = $"<{ property.Name }>k__BackingField"; var field = property.DeclaringType.GetField(backingFieldName, bindingFlags); var compilerAttr = field?.GetCustomAttribute <CompilerGeneratedAttribute>(true); return(compilerAttr != null ? field : null); }