desmondische
desmondische

Reputation: 266

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

Upvotes: 1

Views: 91

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1064204

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.

Upvotes: 3

Dialecticus
Dialecticus

Reputation: 16779

It doesn't matter if you use a class or a struct. Just pick one. These constants are grouped together in a new struct (or class), because this grouping makes more sense than placing them in existing struct (or class)

Upvotes: 1

Related Questions