Reader Level:
Articles

Effective C#: Working with Strings

By Mahesh Chand on March 12, 2001
Using string might degrade the performance of your application. This article explains about what precautions you should take when you are going to use strings in your application.
  • 0
  • 0
  • 32804

Empty String

Checking if a string is empty or not is a basic programming need. The effective way to check if a string is empty or not is to use the Length property of the string class, instead of using null or comparing with " " string.

string str1 = AMethodReturnsString()
{

// Do something and return a string
}
if (str1.Length >0 )
{
// do something
}

String Concatenation

Whenever you modify a String it returns a new string as the result. Creating many String objects might degrade the performance of your program. You can avoid creating a new instance of String by using the StringBuilder class.

Say you want to concatenate two strings. Here is the traditional way -

string str1 = "I like ";
string str2 = "Soccer";
string strConcat = string.Concat(str1, str2);

The value of strConcat = "I like Soccer". You can use the StringBuilder class and its Append method to do the same.

StringBuilder MyStrBuilder = new StringBuilder ("I like ");
String newStr = "Soccer";
MyStrBuilder.Append(newStr);

The value of MyStrBuilder is "I like Soccer".

Comparing String

Use string.Equals method to compare two strings.

string str1 = AMethodReturnsString()
if (str1.Equals("TestSting") )
{
// do something
}

Mahesh Chand

Mahesh Chand is founder of C# Corner. C# Corner founded in 1999 is a FREE member contributions based open platform for developers to solve problems, learn new technology and hang out.  Mahesh has been awar... Read more

COMMENT USING

Trending up