Home >Backend Development >C++ >What Does the Question Mark Mean When Used with Value Types in C#?
The role of question marks in C# value types
While the question mark is typically used in conditional statements (e.g., x ? "yes" : "no" ), it also has a different purpose in the context of value types.
Nullable value type
In C#, a question mark after a value type (for example, int? myVariable) indicates that the value type is nullable. This means that it can represent not only the standard value range of the underlying data type, but also the special null value.
For example, Nullable
Advantages of nullable types
Nullable types have the following advantages:
Example usage
The following code snippet demonstrates the use of nullable integer values:
<code class="language-csharp">class NullableExample { static void Main() { int? num = null; if (num.HasValue) System.Console.WriteLine("num = " + num.Value); else System.Console.WriteLine("num = Null"); int y = num.GetValueOrDefault(); try { y = num.Value; } catch (System.InvalidOperationException e) { System.Console.WriteLine(e.Message); } } }</code>
The above is the detailed content of What Does the Question Mark Mean When Used with Value Types in C#?. For more information, please follow other related articles on the PHP Chinese website!