Manipulating Strings in C#—Finding the String Length
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Finding the String Length
There are times when it's important to find out the length of a string. Usually developers want to know if the string variable has been initialized, and, if it has been initialized, if the length of the string is greater than zero.
To find the length of a string:
- Use the
Lengthproperty of thestringclass. SinceLengthis a property, you don't put parenthesis after the property name (Figure 4.24).
- Use the

- Figure 4.24 The nice thing about having a framework that every language uses is that you use the same command,
Length, to get the size of the string in every language.
Tips
- A string variable that has not been initialized doesn't have a length—its length isn't zero. If you try to ask for the
Lengthof a null variable you will get an error. However, if you initialize the variable to" "then its length will be zero (Figure 4.25).
- A string variable that has not been initialized doesn't have a length—its length isn't zero. If you try to ask for the

- Figure 4.25 This is exactly the reason you should check for
nullbefore calling a method instring. In this case if you callLengthbefore the string has been initialized you will get a runtime exception.
|

