You can do this using PostSharp , here is an example of a field that can only be applied to a public or protected field:
[Serializable] [AttributeUsage(AttributeTargets.Field)] public class MyAttribute : OnFieldAccessAspect { public override bool CompileTimeValidate(System.Reflection.FieldInfo field) { if (field.IsPublic || field.IsFamily) { throw new Exception("Attribute can only be applied to Public or Protected fields"); } return true; } }
source share