Best Practices: Strings in C#

Some “best practices” I follow when working with strings in C#. No rocket science here, but strings are everywhere. In discovering these tidbits over the past year or so working in C#, I had to undo some old habits (accepted idioms from C++) and I wanted to share what I’ve learned.

String Initialization
DO initialize strings as they are a reference type and are initialized to null by default.

string str; // str is initialized to null by default
if (str.Length > 0) // throws a null exception

DO initialize strings with string.Empty.

string str = string.Empty;

Only one (static) instance of string.Empty exists in the entire application.

Do NOT initialize strings with an empty double quotes.

string str = "";

According to Brad Abrhams, String.Empty vs “”, this creates a new string object instance each time the literal “” is used. Probably not a big deal here and there, but do it enough times (in a loop or in a frequently called function) and it will add up.

Checking Strings
In my nomenclature, a string object is defined if it is not null. A string is empty if it is defined and it has zero length. Of course, a non-empty string is defined and has a length greater than zero.

DO use the static method IsNullOrEmpty to test strings.

string str1;
string str2 = string.Empty;
string str3 = ""; // a DO NOT from above
string str3 = "Hello, world!";

if (string.IsNullOrEmpty(str1)) ... // returns true
if (string.IsNullOrEmpty(str2)) ... // returns true
if (string.IsNullOrEmpty(str3)) ... // returns true
if (string.IsNullOrEmpty(str4)) ... // returns false

AVOID testing strings piecemeal and prefer to use IsNullOrEmpty for consistency.

  • if (str != "") unnecessarily creates a new string instance (as described above).
  • if (str != null) checks if string is defined, but does not necessarily mean that string has content.
  • if (str.Length > 0) throws a null exception if str is not defined.
  • if (str.Empty) throws a null exception if str is not defined.
  • if (str == null && str.Length == 0) works, but why not use IsStringNullOrEmpty(str) instead?

Building up Strings
DO use the StringBuilder class to build up a string from pieces.

StringBuilder result = new StringBuilder();
result.Append("Hello");
result.Append(", ");
result.Append("world!");
Console.WriteLine(result.ToString());

In this code snippet, two objects were created: one StringBuilder object and one string object created at the end via ToString().

DO NOT use string concatenation (Concat method or + operator) to build up strings.

string result = "Hello" + ", " + "world";
Console.WriteLine(result);

In this code snippet, four string objects were created: (1) result, (2) "Hello", (3) ", ", and (4) "world". The difference is negligible in this trivial example, but this can balloon into a resource issue in a more complex string construction, especially if the construction is repeated in a loop and/or called frequently in a method. This is one of those things where getting in the habit will prevent the problem from ever arising.

Coding Style: string vs String
string is an alias for System.String. I prefer to use string exclusively. My rationale: int is an alias for System.Int32 and I always write int and never Int32. A misconception/gotcha if you know Java: in Java, int and Integer are two different things. A Java int is a value/primitive type, while a Java Integer is a pointer/reference type. In C#, this distinction does not exist: int is purely an alias for Int32 and likewise, string is an alias for String.

Comparing Strings for Equality
Method 1: if (str1.Equals(str2)) ...
Method 2: if (str1 == str2) ...
Both methods are equivalent if both str1 and str2 are defined (not null). Although string is a reference type, the == operator will compare the values of the string (instead of the object instances/addresses). This is by definition of the language, for developer convenience. Note: if str1 and str2 are null, str1.Equals(str2) will throw a null exception, while str1 == str2 will evaluate to true. Neither way is better: just beware of the side effects.

Advertisement

Comments

One Comment so far. Leave a comment below.
  1. satya,

    it is good for Beginners

Add Your Comments

Disclaimer
Your email is never published nor shared.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Tips

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Ready?

Follow

Get every new post delivered to your Inbox.