DEV Community 👩‍💻👨‍💻

Cesar Codes
Cesar Codes

Posted on

Using C# attributes and reflection for model validation

Attributes are a powerful tool for C# developers. I was recently working on an integration in which I had to do some truncation during serialization. Without getting into specifics, let's go over a simple example scenario.

Let's say you want to validate the maximum field length for a string property. There's different ways to accomplish this, but in some situations you could utilize reflection. In the gist below, I have defined a custom attribute named MyLengthAttribute that simply sets a value on the attribute. I then have a model named MyDataModel with properties that utilize this attribute and pass it the int value. On the Main() method, I am using reflection to dynamically check the properties for this attribute and when my criteria is met, I am printing out some output, which in this example would be:

PropertyB has an invalid value "12345" with length of 5 when max length is 4.

This is a simple example, but I hope that you can see the potential use cases from this.

Happy Coding,

Top comments (0)

DEV has this feature:


Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠