Home > Backend Development > C++ > What Does the Question Mark Mean in C# Value Types (e.g., `int?`)?

What Does the Question Mark Mean in C# Value Types (e.g., `int?`)?

Barbara Streisand
Release: 2025-01-26 08:51:10
Original
770 people have browsed it

What Does the Question Mark Mean in C# Value Types (e.g., `int?`)?

C# Value Type Question: Understand the empty type

Question mark "?" Play a variety of characters in programming, including the use in conditional sentences. However, it also appears in the value type, such as

. In this case, what is the role of this question mark? public int? myProperty

Can empty type

The question mark behind the value type indicates that it is a empty type. Can empty type is a special example of the structure, which can accommodate the entire effective range of the underlying type, and a special vacancy.

This function is particularly useful when processing database scenarios or other elements that may intentionally lack value. For example, a database list that allows Boolean values ​​may contain True, FALSE, or NULL. System.Nullable

sample code

Consider the following code fragment:

Here, Variables are defined as an air -available integer (

), which can save an integer or NULL value.

The attribute allows us to check whether the variable contains effective values. If is True, we can use
class NullableExample
{
    static void Main()
    {
        int? num = null;

        // 判断 HasValue 是否为 true
        if (num.HasValue)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        // 如果 num 为 null,则赋值默认值 0
        int y = num.GetValueOrDefault();

        // 如果 num.HasValue 为 false,则抛出 InvalidOperationException
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}
Copy after login
to get the actual value. Otherwise, is considered NULL.

The above is the detailed content of What Does the Question Mark Mean in C# Value Types (e.g., `int?`)?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template