I created a “const” for a value previously explicitly stated several times in my code:
private static readonly int QUARTER_HOUR_COUNT = 96;
When I did a search-and-replace of 96 for QUARTER_HOUR_COUNT, I inadvertently also replaced the declaration, so it became:
private static readonly int QUARTER_HOUR_COUNT = QUARTER_HOUR_COUNT;
…yet it compiled. I would think that it would disallow that. Why was it accepted by the compiler as a valid declaration?
Presumably because the language specification allows it. Do you have a specific rule in the language specification which you think prohibits it?
If your question is really “why doesn’t the language specification prohibit this” – I suspect it’s because it’s probably quite hard to make sure you only prohibit things you really want to prohibit, while actually prohibit all such things.
You could argue that for simple cases of assignment directly back to itself, it would be good to have a special case in the language spec, but it would introduce complexity into the language for relatively little benefit.
Note that even if you didn’t get an error, I’d expect you to get a warning – something like this:
Also note that if you make it a
constinstead of just a static readonly variable, then you do get a compile-time error:Also note that by .NET naming conventions, this ought to be called
QuarterHourCount, rather than having a SHOUTY_NAME.