I need to check if property has specific attribute defined in its buddy class:
[MetadataType(typeof(Metadata))]
public sealed partial class Address
{
private sealed class Metadata
{
[Required]
public string Address1 { get; set; }
[Required]
public string Zip { get; set; }
}
}
How to check what properties has defined Required
attribute?
Thank you.
It can be done using exploration of nested types:
public IEnumerable<PropertyInfo> GetRequiredProperties()
{
var nestedTypes = typeof(Address).GetNestedTypes(BindingFlags.NonPublic);
var nestedType = nestedTypes.First(); // It can be done for all types
var requiredProperties =
nestedType.GetProperties()
.Where(property =>
property.IsDefined(typeof(RequiredAttribute), false));
return requiredProperties;
}
Usage example:
[Test]
public void Example()
{
var requiredProperties = GetRequiredProperties();
var propertiesNames = requiredProperties.Select(property => property.Name);
Assert.That(propertiesNames, Is.EquivalentTo(new[] { "Address1", "Zip" }));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With