A co-worker just created the following construction in C# (the example code is simplified). His goal was to shorten the notation for all predefined strings in the rest of the code.
public struct PredefinedStrings
{
public const string VeryLongName = "Very Long Name";
public const string AnotherVeryLongName = "Another Very Long Name";
public const string TheLastVeryLongName = "The Last Very Long Name";
}
public static void MethodThatUsesTheNames()
{
Console.WriteLine(PredefinedStrings.VeryLongName);
Console.WriteLine(PredefinedStrings.AnotherVeryLongName);
Console.WriteLine(PredefinedStrings.TheLastVeryLongName);
}
Although it seems to work fine for him, I can't stop wondering whether he should have used a static class instead of a struct or if there's a more elegant way to achieve this.
What would be the preferred way to do this? Please also explain why.
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
.