C# 10 - Difficulty with Custom Attribute Reflection to Enforce Property Naming Conventions in a DTO
I've been banging my head against this for hours. I've searched everywhere and can't find a clear answer. Quick question that's been bugging me - I keep running into I'm working on a .NET 6 application where I need to enforce naming conventions for properties in my Data Transfer Objects (DTOs) using custom attributes. I created a custom attribute called `PropertyNameConventionAttribute` that validates whether the property names follow a specific naming convention (e.g., PascalCase). However, I'm encountering issues when trying to reflect over the properties of my DTOs to validate these conventions. Hereβs a simplified version of my code: ```csharp [AttributeUsage(AttributeTargets.Property)] public class PropertyNameConventionAttribute : Attribute { public string Pattern { get; } public PropertyNameConventionAttribute(string pattern) { Pattern = pattern; } } public class UserDto { [PropertyNameConvention("^[A-Z][a-zA-Z0-9]*$")] public string UserName { get; set; } [PropertyNameConvention("^[A-Z][a-zA-Z0-9]*$")] public string emailAddress { get; set; } // Incorrect naming } public class NamingConventionValidator { public void Validate(object dto) { var properties = dto.GetType().GetProperties(); foreach (var property in properties) { var attribute = property.GetCustomAttributes(typeof(PropertyNameConventionAttribute), false).FirstOrDefault() as PropertyNameConventionAttribute; if (attribute != null) { var regex = new Regex(attribute.Pattern); if (!regex.IsMatch(property.Name)) { throw new ArgumentException($"Property '{property.Name}' does not follow the naming convention."); } } } } } ``` When I run the `Validate` method on an instance of `UserDto`, I expect it to throw an exception for `emailAddress`, but it is not being validated at all. Iβm not seeing any exceptions, and it looks like the reflection check is not picking up the attribute on that property. Iβve checked the following: 1. The attribute is correctly marked on the `emailAddress` property. 2. The regex pattern is accurate for PascalCase validation. 3. I'm not modifying the property names at any point. The only output I get is the successful validation of `UserName`, and nothing for `emailAddress`. I would appreciate any insights into why the reflection is not recognizing the attribute on `emailAddress` or if there's a better approach to enforce these conventions in my DTOs. Could this be related to how I implemented the regex or the way attributes are fetched in reflection? Any help would be greatly appreciated! This is my first time working with Csharp LTS. Thanks for your help in advance! For reference, this is a production CLI tool. Any feedback is welcome! I recently upgraded to Csharp stable.