With the struct
solution, there's nothing to stop some other code doing new PredefinedStrings()
, which won't do anything bad, but is something it's semantically confusing to allow. With a static class the compiler will forbid creation for you. And it goes without saying that static class is the preferred way of providing constants in the Framework.
edit to add, I said that second part without evidence - I have since searched and reasonably quickly found System.Net.Mime.DispositionTypeNames
and System.Net.WebRequestMethods.Http
.
I would prefer the strings all being in a resource file and not embedded within the code - primarily for internationalisation reasons. This can then be accessed via a static class with the values as property members.
Besides a static class
and struct
, why not consider using resource
files for constant strings? These can be accessed very easily as SomeNamespace.ResourceName.KeyName
, and depending on where they are located in your project can be managed externally without recompiling if need be...
Simple rule of thumb: never use structs until you have no other choice.
Constants have a couple of drawbacks:
I would write your code like this (notice rename refactoring too):
public static class KnownNames
{
public static readonly string VeryLong = "Very Long Name";
public static readonly string AnotherVeryLong = "Another Very Long Name";
public static readonly string TheLastVeryLong = "The Last Very Long Name";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With