Day 21 of 30-Day .NET Challenge: StringComparison
Tags: dotnet, aspnet, csharp, programming
Published: 2024-04-09 07:44:00

The article demonstrates the importance of using StringComparison options for efficient string comparison in .NET

## Introduction

Whether it's searching, sorting or equality; how you compare strings can significantly impact your application performance. The article demonstrates the importance of using StringComparison options for efficient string comparison in .NET

### Learning Objectives

* The Problem with Inefficient String Comparisons

* Efficient String Comparison with StringComparison

* Choosing the Right StringComparison Option

### Prerequisites for Developers

* Basic understanding of C# programming language.

[30 Day .Net Challenge](https://singhsukhpinder.medium.com/list/52a751260fe1)

## Getting Started

### The Problem with Inefficient String Comparisons

Consider the following common approach used by most developers for string comparison:
```csharp
    // Inefficient string comparison
    bool equal = string1.ToLower() == string2.ToLower();
```
* The ToLower method creates a new string memory allocation for each comparison, leading to unnecessary allocations. Consider a method with frequent requests that can degrade the application performance.

* The ToLower method is culture-sensitive, which means it might produce different results depending on the current culture set in the executing thread.

### Efficient String Comparison with StringComparison

.NET provides a powerful enumeration, StringComparison, designed to address these inefficiencies.
```csharp
    // Efficient string comparison
    bool equal = string.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);
```
The aforementioned addresses both of the problems in the old string comparison way. 

* No Unnecessary Allocations

* Improved Performance

### Choosing the Right StringComparison Option

* **Ordinal:** Use for most general-purpose comparisons where cultural rules are not relevant. This is the fastest option.

* **OrdinalIgnoreCase:** Ideal for case-insensitive comparisons where cultural rules do not apply.

* **CurrentCulture and CurrentCultureIgnoreCase: **Use when comparing strings displayed to the user, where adherence to cultural rules is important.

* **InvariantCulture and InvariantCultureIgnoreCase:** Suitable for scenarios requiring consistency across different cultures, such as storing and retrieving data.

Create another class named StringComparisons and add the following code snippet
```csharp
    public static class StringComparisons
    {
        private static readonly string string1 = "test";
        private static readonly string string2 = "test";
        public static void BadMethod()
        {
            // Inefficient string comparison
            bool equal = string1.ToLower() == string2.ToLower();
            Console.WriteLine($"In bad method strings are {equal}");
        }
    
        public static void GoodMethod()
        {
            // efficient string comparison
            bool equal = string.Equals(string1, string2, System.StringComparison.OrdinalIgnoreCase);
            Console.WriteLine($"In good method strings are {equal}");
        }
    }
```
Execute from the main method as follows
```csharp
    #region Day 21: String Comparisons
    static string ExecuteDay21()
    {
        StringComparisons.BadMethod();
        StringComparisons.GoodMethod();
    
        return "Executed Day 21 successfully..!!";
    }
    
    #endregion
```
Console output
```
    In bad method strings are True
    In good method strings are True
```
## Complete Code on GitHub
[GitHub — ssukhpinder/30DayChallenge.Net](https://github.com/ssukhpinder/30DayChallenge.Net/tree/main)

### C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

Follow us: [Youtube](https://www.youtube.com/channel/UCejYGg4gAOa1uPAObFuk1HQ) | [X](https://twitter.com/sukhsukhpinder) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh/) | [Dev.to](https://dev.to/ssukhpinder) 
Visit our other platforms: [GitHub](https://github.com/ssukhpinder) 
More content at [C# Programming](https://medium.com/c-sharp-progarmming)