What is the yield keyword used for in C#?

The yield keyword actually does quite a lot here.

The function returns an object that implements the IEnumerable<object> interface. If a calling function starts foreaching over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.

The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:

public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());
}
} public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}

When you step through the example, you'll find the first call to Integers() returns 1. The second call returns 2 and the line yield return 1 is not executed again.

Here is a real-life example:

public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
{
command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return make(reader);
}
}
}
}
}
  • In this case that would be easier, i'm just using the integer here to show how yield return works. The nice things about using yield return is that it's a very quick way of implementing the iterator pattern, so things are evaluated lazly. – Mendelt Dec 22 '08 at 8:35
  • Also worth noting you can use yield break; when you don't want to return any more items.

https://stackoverflow.com/a/39507/3782855

Recently Raymond Chen also ran an interesting series of articles on the yield keyword.

While it's nominally used for easily implementing an iterator pattern, but can be generalized into a state machine.

No point in quoting Raymond, the last part also links to other uses (but the example in Entin's blog is esp good, showing how to write async safe code).

What is the yield keyword used for in C#?的更多相关文章

  1. Behind the scenes of the C# yield keyword(转)

    https://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/ Behind ...

  2. What is the use of c# “Yield” keyword ?

    What is the use of c# “Yield” keyword ? “Yield keyword helps us to do custom stateful iteration over ...

  3. .NET中的yield关键字

    浅谈yield http://www.cnblogs.com/qlb5626267/archive/2009/05/08/1452517.html .NET中yield关键字的用法 http://bl ...

  4. Python关键字yield详解以及Iterable 和Iterator区别

    迭代器(Iterator) 为了理解yield是什么,首先要明白生成器(generator)是什么,在讲生成器之前先说说迭代器(iterator),当创建一个列表(list)时,你可以逐个的读取每一项 ...

  5. [Python学习笔记-005] 理解yield

    网络上介绍yield的文章很多,但大多讲得过于复杂或者追求全面以至于反而不好理解.本文用一个极简的例子给出参考资料[1]中的讲解,因为个人觉得其讲解最为通俗易懂,读者只需要对Python的列表有所了解 ...

  6. Python yield解析

    Pyhton generators and the yield keyword At a glance,the yield statement is used to define generators ...

  7. yield return,yield break

    转自, http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html yield return 表示在迭代中下一个迭代时返回的数据,除此 ...

  8. Beginning Scala study note(2) Basics of Scala

    1. Variables (1) Three ways to define variables: 1) val refers to define an immutable variable; scal ...

  9. PHP生成器Generators

    下文的第一个逐行读取文件例子用三种方式实现;普通方法,迭代器和生成器,比较了他们的优缺点,很好,可以引用到自己的代码中 ,支持的php版本(PHP 5 >= 5.5.0) 后面的yield讲解, ...

随机推荐

  1. WebService 的发布和调用

    WebService 四种发布方式总结 :https://blog.csdn.net/zl834205311/article/details/51612207 调用webService的几种方式 ht ...

  2. git 打tag标着版本

    1.git tag v1.0 2.git push origin v1.0

  3. JDBC课程4--使用PreparedStatement进行增删查改--封装进JDBCTools的功能中;模拟SQL注入 ; sql的date()传入参数值格式!

    主要内容: /*SQL 的date()需要传入参数值: preparedStatement().setDate(new java.util.Date().getTime()); 熟悉了使用Prepar ...

  4. 详细讲解vue.js里的父子组件通信(props和$emit)

    在进入这个话题之前,首先我们先来想一下在vue里,如何写一个父子组件.为了简单起见,下面的代码我都没用脚手架来构建项目,直接在html文件里引入vue.js来作为例子.父子组件的写法如下: <d ...

  5. dos中查找端口的PID,并在任务管理器中处理端口

    本文来源https://www.cnblogs.com/lsyf/p/8979012.html 1.查看所有端口进程 首先点击开始菜单选择运行,接着在运行对话框中输入“cmd”,回车打开命令提示符窗口 ...

  6. 使用宏定义来判断是a和b 的大小

    #include <stdio.h> #include <math.h> #define MAX(a, b) (a) > (b) ? printf("a > ...

  7. webpack 配置react脚手架(二):热更新

    下面继续配置 webpack dev server    hot module replacement: 首先配置dev-server     安装     npm i webpack-dev-ser ...

  8. 第113题:路径总和II

    一. 问题描述 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径. 说明: 叶子节点是指没有子节点的节点. 示例: 给定如下二叉树,以及目标和 sum = 22, 5 ...

  9. yum安装出现No package crontabs available解决办法

    其意思是:yum中不存在这个包 所以解决办法是 1.更新yum   更新yum仓库: yum -y update 2.查看包名在yum中是什么   yum search  all crontabs

  10. [React + GraphQL] Use useLazyQuery to manually execute a query with Apollo React Hooks

    When using useQuery from Apollo React Hooks, the request will be sent automatically after the compon ...