1
\$\begingroup\$

0) Problem / Current Solution

I'd like to create two strings that are really similar like this (demo):

private const string Base = 
@"AAA
CCC";

private const string BasePlusExtra = 
@"AAA
BBB
CCC";

This solution is perfectly fine as is, but doesn't feel very DRY.

Also, in reality, the AAA and CCC sections are very long and identical in both strings.

So, I'd like to make this more reusable.

1) Const String Interpolation (demo)

I could split up the top and bottom half into their own parts and then glue them all together like this:

private const string BaseTop = "AAA";
private const string BaseBottom = "CCC";

private const string Base = 
@$"{BaseTop}
{BaseBottom}";

private const string BasePlusExtra = 
@$"{BaseTop}
BBB
{BaseBottom}";

The problem is, it's hard to get a feel for what the entire string looks like at a quick glance.

2) String Generator (demo)

I could generate the string from a method and even expose both variants through a read only property like this:

private static string Base => GetBase();
private static string BasePlusExtra => GetBase(true);
    
private static string GetBase(bool includeExtra = false)
{
    return $@"AAA
{(includeExtra ? "BBB" : "")}
CCC";
}

The problem here is perf. These are long strings, and I'd rather declare as const to prevent inline initializations.


Do either option 0,1,2 seem preferable? Is there a more elegant way to do this?

\$\endgroup\$
3
  • 3
    \$\begingroup\$ Are you sure that string concatenation is a performance problem? Have you profiled? How big exactly are these strings? They should probably be stored in resources or on the filesystem rather than in string literal constants in the code. And where is this string going? Out to another file, the network, something else? \$\endgroup\$
    – Reinderien
    Mar 23, 2022 at 0:22
  • 3
    \$\begingroup\$ This is all hypothetical enough to be borderline off-topic, unfortunately, unless we get a grip on the above. \$\endgroup\$
    – Reinderien
    Mar 23, 2022 at 0:23
  • \$\begingroup\$ The biggest advantage of the first one is that the two constants can have separate evolutions. For example you can change BasePlusExtra suffix without affecting Base. Based on my experiences most of the time it does not worth the effort to minimize duplications for constants. \$\endgroup\$ Mar 23, 2022 at 7:37

0

Browse other questions tagged or ask your own question.