string型の内容を出力したいが、nullの場合は"(null)"と出力する
OLD1
class Program
{
static void Main(string[] args)
{
string a = "We are the Hello World";
if (a == null)
{
System.Diagnostics.Debug.WriteLine("(null)");
}
else
{
System.Diagnostics.Debug.WriteLine(a);
}
}
}
OLD2
class Program
{
static void Main(string[] args)
{
string a = "We are the Hello World";
System.Diagnostics.Debug.WriteLine(a == null ? "(null)" : a);
}
}
NEW
class Program
{
static void Main(string[] args)
{
string a = "We are the Hello World";
System.Diagnostics.Debug.WriteLine(a ?? "(null)");
}
}
Result
We are the Hello World・?? はnull合体演算子という。オペランドが null 以外の場合、左オペランドを返し、それ以外の場合は右オペランドを返す。
・C#にしかないようなので汎用性は低い。
引用元:
C#ショートプログラミング
0 件のコメント:
コメントを投稿