Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khởi tạo Tuple rỗng trong C#

Tuple (class) là reference type, có thể null:

Tuple<string, string> myTuple; // null

Hoặc gán explicit null:

Tuple<int, string> tuple = new Tuple<int, string>(10, null);

Ví dụ kiểm tra null

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Tuple<int, string> tuple = new Tuple<int, string>(10, null);
            
            if (tuple.Item1 == 10) Console.WriteLine(tuple.Item1);
            if (tuple.Item2 == null) Console.WriteLine("Item2 is null");
        }
    }
}

ValueTuple (C# 7+) - struct, không nullable mặc định:

// Nullable ValueTuple
(int, string)? tuple = null;
(int, string?) tuple2 = (10, null);

// Default (zero-initialized)
var tuple3 = default((int, string)); // (0, null)

Khác biệt: Tuple class = reference type (nullable), ValueTuple = value type (non-nullable, dùng ? cho nullable).