psychoric still trying to figure out what this blog is about

Diving diving diving
26Jan/082

coalescing null yield return

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

Comments (2) Trackbacks (0)
  1. 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?

  2. 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


Leave a comment


No trackbacks yet.