I have a class Constants in which I store a number of static readonly variables.
Should I do this:
private static readonly int _maxThings = 100;
...
public static int MaxThings { get { return _maxThings; } }
That seems kind of redundant to me. Is there any reason why I wouldn’t just do the following?
public static int MaxThings { get { return 100; } }
Edit
Okay, so this was a brain fart of a question. I think the point is that if I’m going to be setting this value at initialization then it makes sense to use a static backing field and expose a public get-only property that wouldn’t need to be static itself.
If, however, I’m comfortable setting a public static property to a hard value, then there’s no functional difference between that and just baking it into the assembly. Unless there’s some other concept I’m missing here, in this case I’d just use a const.
Thanks for the answers.
you should do
public const int MaxThings = 100;there is no reason that i can see to use properties in this case.
Update ->
In response to comments.. If you are developing a library and exporting constants then it’s important to understand how constants are consumed int .net. When compiled against your library, the constant values will be inlined and included in the consuming application, such that if your library is updated and consuming application is not then the old constant values will still be present. This is, of course, when static properties should be used.
If you are not developing a library, then the use of const’s are fine.