says: "end of 2008, and I did no shyt.."

coalescing null yield return

January 26th, 2008

Ok the title means nothing at all, and they are not related too, except that they both are of C# family. As requested by Klaw, i am going to blog about it so that we all learn :D

Coalescing Null Operator

You are probably thinking what’s that. Maybe it is just me, but it is one of the cool subtle features in C# that I just discovered today. Shame on me ya. Basically you all are familiar with this:

string myStrVarB = (myStrVarA == null) ? "null string" : myStrVarA

So with coalescing null operator (??), you can shortened it to:

string myStrVarB = myStrVarA ?? "null string"

Let’s see, that is saving of 17 characters. Your boss sure will praise you for that :D On a side note, in case you don’t know, you can allow a scalar type to be null by using the nullable operator:

int? myInteger = null

yield return

Definition from MSDN: “Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration”. I assume you have previous knowledge with IEnumerable (or iterator), so i am not going into detail with it. The yield statement appears only inside an iterator block and returns the value that is expected by the calling foreach statement. Cut the theory and show me the example.

public static IEnumerable Power(int number, int exponent)
{
	int counter = 0;
	int result = 1;
	while (counter++ < exponent)
	{
		result = result * number;
		yield return result;
	}
}

static void Main()
{
	// Display powers of 2 up to the exponent 8:
	foreach (int i in Power(2, 8))
	{
		Console.Write("{0} ", i);
	}
}

There you go, another simple bit of my learning :D

  1. 2 Responses to “coalescing null yield return”

  2. By Klaw on Jan 26, 2008

    it took me 10 seconds to realize < was htmlencoded. hahaa. remember to encode with “pre” tag in code block :P

    so the result of the yield return result is
    2
    4
    8
    16
    32
    64
    128
    256

    Or did I just embarrass myself in cyberspace?

  3. By Eric on Jan 27, 2008

    Oops my bad. First time with code highlight with WP and it ain’t easy.

    You got it right. The return result is so ;) But no prize for you la :P

Post a Comment