C# – Is it a good idea to use strings in a struct as values to static properties

cheappropertiesstackstrings

I'm in a discussion with a co-worker concerning the use of structs. I have a couple of structs that contain several static properties that are used throughout our website. The value of those properties are all strings. They're not very long, the longest value has 29 characters.

His argument: "I am saying there is no performance gain because there are strings inside of them. For value types yes you gain memory/gc benefits. With strings they are ref types so allocate to the heap and won't give any benefit."

My argument: "…I'm simply treating the string values as value types by using the struct, therefore saving time and gaining performance by not having to instantiate it every time."

Here is an example of one of the structs so that you can see how I'm using them:

public struct Hero
{
    public static string Image          = "Hero Image";
    public static string Eyebrow        = "Hero Eyebrow";
    public static string Heading        = "Hero Heading";
    public static string Subheading     = "Hero Subheading";
    public static string YoutubeLink    = "Youtube Hero Link";
    public static string PardotForm     = "Pardot Form Hero Link";
    public static string PardotDirect   = "Pardot Direct Hero Link";
    public static string DirectLink     = "Direct Hero Link";
    public static string FacebookLink   = "Hero Facebook Link";
    public static string TwitterLink    = "Hero Twitter Link";
    public static string LinkedInLink   = "Hero LinkedIn Link";
    public static string LinkClassNames = "Class Names";
}

Let me know if I'm completely wrong and should just use classes or if there is a better way of using the structs for my values (i.e: readonly instead of static, etc…).

Best Answer

I'll assess what you both said:

  • For value types yes you gain memory/gc benefits.

    True.

  • With strings they are ref types so allocate to the heap and won't give any benefit.

    True.

  • ..I'm simply treating the string values as value types by using the struct

    This doesn't make sense. You can't "treat" as value types or reference types. That's determined by how String is implemented. Given that String is read-only and un-subclassible in most programming languages, it usually has value semantics (even if it is really implemented as a reference to a heap object"

  • therefore saving time and gaining performance by not having to instantiate it every time.

    The struct doesn't matter here. String constants are in a static portion of the program, they're not subject to garbage collection, and they're not on the heap.

Putting these strings in struct vs. a class doesn't matter. As long as they're string constants, they're lazily initialized the first time the struct/class is references.