In C#, ? is a multi-purpose symbol with a variety of different uses, depending on the context. Here are some common uses:
1. Nullable Types
? Can be used to change value types (such as int, bool, etc.) to nullable types. For example, int? represents an integer that can be null.
int? nullableInt = null; nullableInt = 5;
2. Null-conditional operator
?. Used to check whether the object is null first when accessing members of an object (such as properties or methods) to avoid NullReferenceException.
string str = null; int? length = str?.Length; // length Will be null,because str yes null
3. Null-coalescing operator
?? is used to return the default value on the right when the expression on the left is null.
int? nullableInt = null; int value = nullableInt ?? 10; // value will be 10, because nullableInt is null
4. Optional parameters in the event handler (not directly expressed by ?, but related)
In event handlers, the EventArgs parameter can usually be ignored by defining a processor without parameters, which has nothing to do with ?, but parameters can be omitted when subscribing to events.
public event EventHandler MyEvent; void OnMyEvent() { MyEvent?.Invoke(this, ); // Use the empty condition operator to safely call events}
5. Is expressions in pattern matching (C# 7.0 and above)
In type pattern matching, the is keyword can be combined with ? for type checking and conversion, but here ? is part of the type pattern and is used to represent nullable types.
object obj = 5; if (obj is int? nullableInt && ) { ($"Value: {}"); }
6. Ternary Operator
Although the ternary operator itself does not use ? as "purpose", it is part of the ? : structure for simple conditional judgment.
int a = 10, b = 20; int max = (a > b) ? a : b; // max will be 20
? It is mainly used in C# to handle nullability and null value checks, helping developers write more robust and safe code.
This is the end of this article about the six uses of C#. For more related C# content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!