Search code examples
c#structconstantsstatic-classes

Why use struct to hold constants, and not a static class?


I've just noticed two struct objects, JwtHeaderParameterNames and JwtRegisteredClaimNames, whose only purpose is to store string constants.

  1. Why did they make them structs rather than static classes, even though there are already some static classes for constants in the namespace?

  2. Why would you make a struct that contains only constants or static members?

Thanks


Solution

  • You're right in that the more idiomatic way of expressing this would be static class; having a struct with no fields but with these const entries is unusual and atypical. It won't actually harm anything, but it is a little weird to be able to do new JwtHeaderParameterNames() or new JwtRegisteredClaimNames(), which serve no purpose.

    I'm kinda surprised it wasn't changed to static class during the review process. If there is a good reason that is relevant to this specific usage, I would expect a comment in the code (also), but I don't see one. In the absence of that: we could only speculate.

    Interestingly WsTrustConstants works more like we would expect, making it even more of an oddity. It is likely that this oddness is known and acknowledged, but cannot be changed now without making it a breaking change.