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

Tạo mảng chuỗi rỗng trong C#


Giới thiệu

Mảng chuỗi rỗng (empty string array) khai báo bằng new string[0] hoặc new string[] { }. Length = 0, không phải null.

Ví dụ cơ bản

string[] str = new string[] { };
// hoặc
string[] str = new string[0];
// hoặc
string[] str = Array.Empty(); // .NET Core 2.0+, singleton, hiệu suất tốt

Ví dụ hoàn chỉnh

using System;

public class Demo
{
    public static void Main()
    {
        string[] str = new string[] { };
        Console.WriteLine("String Array elements won't display since it's empty...");
        for (int i = 0; i < str.Length; i++)
        {
            string res = str[i];
            Console.WriteLine(res);
        }
    }
}

Kết quả

String Array elements won't get displayed since it's empty...

So sánh các cách tạo mảng rỗng

CáchCú phápƯu điểm
Array literalnew string[] { }Rõ ràng, readable
Size 0new string[0]Tường minh size
Array.Empty (khuyên dùng)Array.Empty()Singleton, không cấp phát, thread-safe

Lưu ý

  • Mảng rỗng != null. str == null -> false.
  • foreach trên mảng rỗng an toàn (chạy 0 lần).
  • Dùng Array.Empty() cho performance critical code (tránh allocation).
  • Trả về mảng rỗng thay vì null từ method (best practice).