Yield keyword in C Sharp

Hi,

 

One of the cool and yet most unknown feature of the C# is the yield keyword. The yield keyword is used in an iterator block to provide a value to the enumerator object or to signal the end of the iteration. When used the expression is evaluated and returned as a value to the enumerator object. Note the expression has to be implicitebly convertible to yield type of the iterator. Here is an example

 
public static IEnumerable<int> GetIntCollectionFromString(string SomeString)
{
    string[] val = SomeString.Split(' ');
    int intVal;
    foreach (string token in val)
    {
        if (int.TryParse(token, out intVal))
        {
            yield return intVal;
        }
        else
        {
            yield break;
        }
    }
}
 

Here since we are using the yield keyword the function will return the collection of intVal instead of the value of intVal. The statement will only return when the iteration of the loop is complete.

 

There are some limitation with the yield keywords.

  1. Unsafe blocks are not allowed
  2. Parameters to the method, operator, or accessor cannot be ref or out.

Vikram

Published Tuesday, February 19, 2008 8:32 AM by vik20000in
Filed under: ,

Comments

# re: Yield keyword in C Sharp

Tuesday, February 19, 2008 4:52 AM by anon

Most unknown feature of the C#???

# re: Yield keyword in C Sharp

Tuesday, February 19, 2008 6:17 AM by Joe Chung

var ints = SomeString.Split(' ').TakeWhile(v => v.IsInt32()).Select(v => int.Parse(v));

once I encapsulate int.TryParse with an extension method

static class Int32Util

{

   static public bool IsInt32(this string value)

   {

       int foo;

       return int.TryParse(value, out foo);

   }

}

I like your generator, because it's one-pass, not two!

# Finds of the Week - February 24, 2008 &raquo; Chinh Do

Tuesday, February 26, 2008 1:11 AM by Finds of the Week - February 24, 2008 » Chinh Do

Pingback from  Finds of the Week - February 24, 2008 &raquo; Chinh Do

# re: Yield keyword in C Sharp

Monday, March 17, 2008 11:01 AM by Sunny Ahuwanya

Did you mean to declare int intVal where int intToAdd appears?

# re: Yield keyword in C Sharp

Tuesday, March 18, 2008 3:44 AM by vik20000in

yes Sunny Ahuwanya

You got it right. I have corretd it now

# re: Yield keyword in C Sharp

Tuesday, November 11, 2008 3:12 PM by Vin

This is the exact same definition from MSDN...you could've just put a link to it.

# re: Yield keyword in C Sharp

Thursday, January 08, 2009 5:14 PM by Green Williams

Someone said that this article is a rip from MSDN. That explains why it hard to understand.

# re: Yield keyword in C Sharp

Tuesday, May 12, 2009 9:08 PM by faisalbaqai

I just added an article about Compiler Sugar of C#. This also covers Yield which I believe is the biggest compiler sugar in C#.

Leave a Comment

(required) 
(required) 
(optional)
(required)