views:

53

answers:

3

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.

A: 

From a code readability standpoint I find the second one to be an improvement. Not sure if the compiler is smart enough to optimize in that situation, but the hit is so negligible I would just go with readability.

Matt
+3  A: 

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.

headsling
See http://stackoverflow.com/questions/755685/c-static-readonly-vs-const - especially @Marc Gravell's answer. If the "constant" may change and is used by other assemblies, you may want to consider static properties.
TrueWill
Agree with TrueWill. If it were private or internal accessibility, I'd say run with it. But public constants are suspicious unless they are truly constant values such as gravitational constants or WM_BLAH symbols.
Josh Einstein
+1  A: 

Because constants are well... constant, the value will never change.

The preference for properties are that the signature of a field and a property are different. So changing from a field to a property requires that all callers are recompiled. Thus creating a property in the first instance will avoid that issue if you need to add getter/setter logic at a later date.

Because you have a constant, which will never change, there is no reason at all to implement it as a property. Although you defined a readonly static, as this can only be changed from within the class, externally there is no difference between that and a constant.

Philip Smith