You may be guilty of taking strings for granted. They’re baked into the framework as a built-in type, and since almost every codebase uses them they tend to just fade into the background. Throughout the years, though, I’ve seen people new to C# use strings in several ways that can be streamlined or improved. This set of mini-tips will drastically improve your dealings with strings.
String mini-tip #1: Static utility methods
You’ve probably already found the utility methods that are available as extension methods, since they show up in Intellisense when working with variables. These include some really useful utility methods like Contains, Substring, and ToLower.
These aren’t all of the built-in utility methods though! On a recent project, I was reviewing code from a developer just learning C#. They needed to combine a list of names retrieved from the backend into a single line for the UI. Not seeing anything helpful on a string variable, this is what they implemented:
This is the wrong approach because there’s already a built-in method to accomplish this in the framework. You have to look on the string class itself to find the right way.
String mini-tip #2: Use verbatim literal strings to easily maintain inlined text
Occasionally, you’ll need to embed a fairly long string into your application. Two sources that I’ve needed to embed have been SQL statements and hardcoded email templates. Both of them spanned multiple lines, leaving me modifying the strings into smaller pieces so I could still read them.
A coworker next to me heard the distinct keyboard rhythm that happens when making the same small edit over and over. They slid over, watched for a couple seconds, and then introduced me to the verbatim literal string.
Notice the @ sign at the beginning? This tells the compiler to treat almost all of the content (everything but a quote escape) as a single string, including carriage returns.
Bonus tip – because the verbatim string ignores escape sequences, you can also use it to simplify any inline directory paths you have.
String mini-tip #3: Use the string’s constructor to easily generate strings
I don’t need this very often, but when I do it’s really useful. Imagine you need to construct a string of a particular length without caring about the actual content. For me this is usually when testing validation logic or data size constraints. You can type out a string and carefully count like this:
Or you can effortlessly use the string class’s constructor to specify how many instances of a certain character you want.
I hope these mini-tips will help you on your quest to become more effective with C# strings!