0
0
CsharpHow-ToBeginner · 3 min read

How to Use StartsWith and EndsWith in C# - Simple Guide

In C#, use StartsWith to check if a string begins with a specific substring, and EndsWith to check if it ends with one. Both methods return a bool indicating true or false based on the match.
📐

Syntax

The StartsWith and EndsWith methods are called on a string variable to check its start or end respectively.

  • bool result = str.StartsWith("text"); checks if str starts with "text".
  • bool result = str.EndsWith("text"); checks if str ends with "text".

Both return true if the condition matches, otherwise false.

csharp
string str = "Hello World!";
bool starts = str.StartsWith("Hello");
bool ends = str.EndsWith("World!");
💻

Example

This example shows how to use StartsWith and EndsWith to check parts of a string and print the results.

csharp
using System;

class Program
{
    static void Main()
    {
        string phrase = "Welcome to C# programming!";

        bool startsWithWelcome = phrase.StartsWith("Welcome");
        bool endsWithProgramming = phrase.EndsWith("programming!");
        bool startsWithHello = phrase.StartsWith("Hello");

        Console.WriteLine($"Starts with 'Welcome': {startsWithWelcome}");
        Console.WriteLine($"Ends with 'programming!': {endsWithProgramming}");
        Console.WriteLine($"Starts with 'Hello': {startsWithHello}");
    }
}
Output
Starts with 'Welcome': True Ends with 'programming!': True Starts with 'Hello': False
⚠️

Common Pitfalls

Common mistakes include:

  • Not considering case sensitivity: StartsWith and EndsWith are case-sensitive by default.
  • Passing null as the argument causes exceptions.
  • Using these methods on null strings causes NullReferenceException.

To avoid case issues, use the overload with StringComparison.

csharp
string text = "Hello World";

// Wrong: case-sensitive check
bool wrongCheck = text.StartsWith("hello"); // returns false

// Right: case-insensitive check
bool rightCheck = text.StartsWith("hello", StringComparison.OrdinalIgnoreCase); // returns true
📊

Quick Reference

MethodPurposeReturnsCase Sensitivity
StartsWith(string value)Checks if string starts with valueboolCase-sensitive by default
EndsWith(string value)Checks if string ends with valueboolCase-sensitive by default
StartsWith(string value, StringComparison comp)Starts with check with case optionboolDepends on StringComparison
EndsWith(string value, StringComparison comp)Ends with check with case optionboolDepends on StringComparison

Key Takeaways

Use StartsWith and EndsWith to check string beginnings and endings in C#.
These methods return true or false based on the match.
They are case-sensitive by default; use StringComparison to ignore case.
Avoid passing null arguments or calling on null strings to prevent errors.
Use the overloads with StringComparison for flexible comparisons.