Practical Methods for Using Switch Statements with String Contains Checks in C#

Dec 01, 2025 · Programming · 11 views · 7.8

Keywords: C# | string contains | switch statement | preprocessing | pattern matching

Abstract: This article explores how to handle string contains checks using switch statements in C#. Traditional if-else structures can become verbose when dealing with multiple conditions, while switch statements typically require compile-time constants. By analyzing high-scoring answers from Stack Overflow, we propose an elegant solution combining preprocessing and switch: first check string containment with Contains method, then use the matched substring as a case value in switch. This approach improves code readability while maintaining performance efficiency. The article also discusses pattern matching features in C# 7 and later as alternatives, providing complete code examples and best practice recommendations.

In C# programming, handling string contains checks is a common task. The traditional approach uses if-else statement chains, such as checking if a message string contains specific keywords. However, as the number of conditions increases, this structure can become verbose and hard to maintain. Many developers wish to use switch statements for simplification, but switch in C# typically requires case values to be compile-time constants, while the return value of string.Contains() is determined at runtime, creating limitations for direct combination.

Problem Analysis and Traditional Methods

Consider a typical scenario: we need to output different responses based on message content. The original code might look like this:

if (message.Contains("test"))
{
    Console.WriteLine("yes");
}
else if (message.Contains("test2"))
{
    Console.WriteLine("yes for test2");
}

This method is straightforward, but as conditions grow, the code becomes lengthy. Additionally, switch statements cannot directly use Contains as a case condition because case values must be constant expressions. For example, attempting switch (message) { case string s when s.Contains("test"): ... } is not feasible in earlier C# versions, although C# 7 introduced pattern matching to enable this, compatibility concerns remain.

Efficient Solution: Combining Preprocessing with Switch

Based on high-scoring answers from Stack Overflow, we propose a practical method: first perform string contains checks, then use the matched substring in a switch statement. The core idea is to transform runtime conditions into compile-time constants. Here are the implementation steps:

  1. Define a string variable to store the matched keyword.
  2. Use conditional logic (e.g., if or FirstOrDefault) to check which keyword the message contains.
  3. Assign the matched keyword to the variable, then use this variable in the switch statement.

Example code:

string message = "test of mine";
string str = "";

if (message.Contains("test"))
    str = "test";
else if (message.Contains("test2"))
    str = "test2";

if (!string.IsNullOrEmpty(str))
{
    switch (str)
    {
        case "test":
            Console.WriteLine("yes");
            break;
        case "test2":
            Console.WriteLine("yes for test2");
            break;
        default:
            Console.WriteLine("nothing");
            break;
    }
}

This method separates condition checking from business logic, improving code modularity. The preprocessing step ensures switch only handles valid constant values, avoiding compilation errors. Moreover, it is easily extensible: adding new keywords only requires updates in preprocessing and switch cases.

Alternative Approaches and Advanced Techniques

Beyond the above method, other answers provide valuable supplements. For example, using a dictionary to map keywords to handler functions:

var dict = new Dictionary<string, Action>();
dict.Add("test", () => Console.WriteLine("yes"));
dict.Add("test2", () => Console.WriteLine("yes for test2"));

string key = dict.Keys.FirstOrDefault(k => message.Contains(k));
if (key != null)
    dict[key]();

This approach suits dynamic keyword management but may add overhead. In C# 8 and later, switch expressions offer more concise syntax:

var result = message switch
{
    string s when s.Contains("test") => "yes",
    string s when s.Contains("test2") => "yes for test2",
    _ => "nothing"
};
Console.WriteLine(result);

However, this requires newer C# version support. The reference article mentions that developers often face case sensitivity issues, recommending normalization with ToUpper() or ToLower(), e.g., message.ToUpper().Contains("SUCCESS").

Performance and Best Practices

When choosing a method, consider performance impacts. The preprocessing approach is efficient in most scenarios as it avoids repeated Contains calls. If the keyword list is large, optimize using dictionaries or arrays. Best practices include:

In summary, combining preprocessing with switch statements offers a solution that balances readability and performance. It is compatible with all C# versions, easy to understand and extend, making it an ideal choice for handling string contains checks.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.