??

http://d.hatena.ne.jp/uskz/20080108/p1
演算子の話題が出ていて、ふとC#の??演算子を思い出しました。
C#2.0でnull許容型が追加された際にあわせて加わったものですが、使われてるところあまり見ないような気もしますね。
とか言ってる自分も、いざコード書くとなるとその存在を忘れてる気が・・・。

int? a = null;
int? b = a ?? 256;
int? c = a != null ? a : 256;
Console.WriteLine( b );
Console.WriteLine( c );

256
256
別にnull許容型以外でも使えます。たとえば・・・

private Foo instance = null;
public Foo Instance
{
	get
	{
		if ( this.instance == null )
			this.instance = new Foo();
		return this.instance;
	}
}
public Foo Instance2
{
	get { return this.instance ?? (this.instance = new Foo()); }
}


または・・・。 (冗談)

Func<string, List<Func<string>>> closure = (x) =>
{
	List<Func<string>> fns = new List<Func<string>>();
	Func<string, bool> contains = ((y) => x.IndexOf(y) != -1);

	fns.Add( () => contains( "hello" ) ? (x + "!") : null );
	fns.Add( () => contains( "world" ) ? (x + "?") : null );
	fns.Add( () => contains( "," ) ? (x + " ;-)") : null );
	return fns;
};

Func<List<Func<string>>, string> getResult =
	(lst) => (lst[0]() ?? lst[1]() ?? lst[2]() ?? "potato");

string result1 = getResult( closure( "hello, world" ) );
Console.WriteLine( result1 );
string result2 = getResult( closure( "hallo, world" ) );
Console.WriteLine( result2 );
string result3 = getResult( closure( "hallo, word" ) );
Console.WriteLine( result3 );
string result4 = getResult( closure( "ハローワーク" ) );
Console.WriteLine( result4 );

hello, world!
hallo, world?
hallo, word ;-)
potato
久々にC#3.0触りたかっただけです。 今は反省しています。


関係ないけど、いまだにC#でのlambda式の書き方が自分の中で定まりません。。
さてバイト切り上げてそろそろ帰ろう。