C# check if String is null or empty – Learning from Code Review

最近的工作主要是做Backend API Library
今日有一個功能..
使用者的input需要輸入一些東西
不能是’ ‘ empty space
所以便要做一些validation 去檢查
以下是我的垃圾寫法

code review 後 同事建議了另一寫法給我
我覺得很好用的 簡單又容易明
Code Review
Silly way to check if string is not null and is not empty

string input = null;

if (input == null || input.Trim() == "")
{
	Console.WriteLine("Input is null or empty");
}
else
{
	Console.WriteLine("Input isvalid");
}
input = " ";
if (input == null || input.Trim() == "")
{
	Console.WriteLine("Input is null or empty");
}
else
{
	Console.WriteLine("Input isvalid");
}

input = " Yeah";
if (input == null || input.Trim() == "")
{
	Console.WriteLine("Input is null or empty");
}
else
{
	Console.WriteLine("Input isvalid");
}



Code Review 後的寫法
用了String.IsNullOrWhiteSpace 來檢查這個variable 有沒有字串

string input = null;

if (String.IsNullOrWhiteSpace(input))
{
	Console.WriteLine("Input is null or empty");
}
else
{
	Console.WriteLine("Input is valid");
}

input = " ";
if (String.IsNullOrWhiteSpace(input))
{
	Console.WriteLine("Input is null or empty");
}
else
{
	Console.WriteLine("Input is valid");
}

input = " Yeah";
if (String.IsNullOrWhiteSpace(input))
{
	Console.WriteLine("Input is null or empty");
}
else
{
	Console.WriteLine("Input is valid");
}



clearer way to check if string is not null and is not empty
Hope you find it useful

Leave a Reply