Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Static class vs struct for predefined strings

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:

  • only simple types can be used (strings, numerics, etc.)
  • constants are injected into referencing assemblies. If you recompile assembly with constants and don't recompile assembly that uses constants, you'll get into trouble

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";
}