c# – How to handle magic numbers across multiple files


I have a multilayered .NET Core project. In each layer there are some classes that contain magic numbers. I know that I can avoid them by creating a constant at the top of the class. But what if you have a constant value that should be used across the whole project?

Let’s assume you want to clamp the length of the user’s username between 1 and 20 characters. You could create a static file e.g.

public static class UserEntityConstants
{
    public static int UsernameMinLength = 1;
    public static int UsernameMaxLength = 20;
}

but how would you group those? One file per entity?

The static file won’t solve the problem that you can’t pass in a value from the static file to annotations

(StringLength(20)) // UserEntityConstants.UsernameMaxLength is not possible here
(Required)
public string Username { get; set; }

So how do you manage the magic numbers?