0
0
CsharpHow-ToBeginner · 3 min read

How to Find Length of String in C# - Simple Guide

In C#, you can find the length of a string using the Length property. This property returns the number of characters in the string, including spaces and special characters.
📐

Syntax

The Length property is used with a string variable to get its size. It returns an integer representing the number of characters.

  • stringVariable.Length: Accesses the length of the string.
csharp
string myString = "Hello";
int length = myString.Length;
💻

Example

This example shows how to get the length of a string and print it to the console.

csharp
using System;

class Program
{
    static void Main()
    {
        string greeting = "Hello, world!";
        int length = greeting.Length;
        Console.WriteLine($"The length of the string is: {length}");
    }
}
Output
The length of the string is: 13
⚠️

Common Pitfalls

Some common mistakes when finding string length in C# include:

  • Trying to call Length() as a method with parentheses, but Length is a property without parentheses.
  • Assuming Length counts bytes instead of characters; it counts characters, including spaces and punctuation.
  • Not checking for null strings before accessing Length, which causes a NullReferenceException.
csharp
string s = null;
// Wrong: int len = s.Length; // Throws NullReferenceException

// Right:
int len = s?.Length ?? 0; // Safely returns 0 if s is null
📊

Quick Reference

Summary tips for using Length property:

  • Use stringVariable.Length to get the number of characters.
  • Do not use parentheses after Length.
  • Check for null before accessing Length to avoid errors.

Key Takeaways

Use the Length property to find the number of characters in a string.
Length is a property, not a method, so do not use parentheses.
Always check if the string is null before accessing Length to prevent errors.
Length counts all characters including spaces and punctuation.