Lesson: C# Conditional Types

What are Conditional Types in C#?

In C#, conditional types allow you to assign different types based on certain conditions. These types are commonly used in scenarios where you want to make decisions about which type to use based on a condition.

Conditional Operator (Ternary Operator)

The ternary operator (`?:`) is the most common example of a conditional type in C#. It works as a shorthand for an `if-else` statement and is used to return one of two values based on a condition. The syntax looks like this:

condition ? value_if_true : value_if_false;

Example:

int age = 20;
string result = (age >= 18) ? "Adult" : "Minor";

In this case, the variable `result` will be set to "Adult" because `age` is 20, which is greater than or equal to 18.

Conditional Types in C#

C# also supports the use of conditional types in generic methods or with type inference. You can use `if-else` conditions to determine the type a variable should be or apply specific methods based on conditions.

Interactive Example

Try changing the value of the age and see how the result updates based on the condition:

Result: Adult

Quiz: Test Your Knowledge on Conditional Types

1. What is the correct syntax for the ternary operator in C#?




2. Which of the following statements about the ternary operator is true?




3. What will the following code output if age = 16?

string result = (age >= 18) ? "Adult" : "Minor";



4. What is the purpose of conditional types in C#?