C# tutorials > Modern C# Features > C# 6.0 and Later > Explain target-typed switch expressions.
Explain target-typed switch expressions.
Target-typed switch expressions, introduced in C# 9.0, enhance the switch expression syntax by allowing the compiler to infer the type of the switch expression based on the context in which it's used. This eliminates the need for explicit casting or type conversions in many scenarios, leading to cleaner and more readable code.
Basic Syntax and Concepts
The switch
keyword is followed by the expression to be evaluated (month
in this case). Each arm of the switch expression uses the =>
operator to specify the result. The compiler automatically infers the return type (string
) based on the context (the return type of the GetSeason
method). The _
discards all other values that are not in the defined ranges and return a default value.
string GetSeason(int month)
{
return month switch
{
12 or 1 or 2 => "Winter",
>= 3 and <= 5 => "Spring",
>= 6 and <= 8 => "Summer",
>= 9 and <= 11 => "Autumn",
_ => "Invalid Month"
};
}
Benefits of Target-Typing
Conciseness: Simplifies the code by reducing the need for explicit type conversions. Readability: Makes the code easier to understand by clearly expressing the intent. Type Safety: Relies on the compiler's type inference, reducing the risk of type-related errors at runtime.
Real-Life Use Case: Processing Different Data Types
This example demonstrates how target-typed switch expressions can be used to process different data types in a single expression. The compiler infers the return type as object
, allowing the switch expression to return values of different types based on the input.
object ProcessData(object data)
{
return data switch
{
int i => i * 2,
string s => s.ToUpper(),
bool b => !b,
_ => throw new ArgumentException("Unsupported data type")
};
}
Advanced Pattern Matching
Target-typed switch expressions work seamlessly with advanced pattern matching features. This example shows how to switch based on properties of an object, providing more complex conditional logic.
public class WeatherData
{
public decimal Temperature { get; set; }
public string Condition { get; set; }
}
string GetWeatherDescription(WeatherData weather)
{
return weather switch
{
{ Temperature: > 25, Condition: "Sunny" } => "Hot and sunny",
{ Temperature: < 0, Condition: "Snow" } => "Freezing and snowy",
{ Temperature: >= 15 and <= 25, Condition: "Cloudy" } => "Mild and cloudy",
_ => "Unknown weather"
};
}
Best Practices
Clarity: Use target-typed switch expressions when they improve the readability and conciseness of your code. Exhaustiveness: Ensure that your switch expression handles all possible input values or provides a default case ( Type Consistency: Ensure all arms of the switch expression return values that are implicitly convertible to the target type._
) to avoid unexpected behavior.
When to Use Them
Use target-typed switch expressions when you need to return a value based on a set of conditions and the type of the return value can be inferred from the context. They are particularly useful when dealing with multiple types or complex patterns.
Alternatives
The traditional Conditional operators (switch
statement is an alternative. However, target-typed switch expressions often provide a more concise and readable syntax, particularly when combined with pattern matching.?:
) can be used for simple cases, but they can become less readable for complex logic. if-else
statements can always achieve the same results but with more verbosity.
string GetSeasonClassic(int month)
{
string season;
switch (month)
{
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Invalid Month";
break;
}
return season;
}
Interview Tip
Be prepared to explain the benefits of target-typed switch expressions over traditional switch
statements and conditional operators. Highlight the improved readability, conciseness, and type safety they provide.
FAQ
-
What version of C# introduced target-typed switch expressions?
Target-typed switch expressions were introduced in C# 9.0. -
Can I use target-typed switch expressions with custom types?
Yes, you can use target-typed switch expressions with custom types, including classes, structs, and records. You can also use pattern matching to switch based on properties of custom types. -
What happens if none of the switch arms match the input?
If none of the switch arms match and there is no default case (_
), the compiler will issue a warning. To avoid unexpected behavior, always include a default case or ensure that your switch expression handles all possible input values.