EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Yield Keyword in C#

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » Yield Keyword in C#

Yield Keyword in C#

Introduction to Yield Keyword in C#

Yield is a contextual keyword in C#. Contextual keywords are those keywords in C# which are not reserved for the complete program. Rather they are reserved keywords for certain parts of the program where the keyword can be relevantly put to use. These keywords can be used as valid identifiers wherever their relevance does not convey any special meaning to the compiler.

The yield keyword indicates that the method or the accessor containing the keyword is an iterator method/accessor. An iterator method/accessor is one that does not return a single value. Rather, it is called in iterations and returns different values in each iteration.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

The syntax of the yield keyword is pretty simple. You simply need to specify the keyword before the return statement of the method or the accessor.

yield return <expression>;

OR

yield break;

These are the two implementations of the keyword. When used with a return statement, the yield keyword returns the next value calculated from the expression, until the exit condition of the expression is met. When used with the break keyword, the yield keyword breaks the iteration and program execution comes out of the method/accessor.

How does Yield Keyword work in C#?

  1. So, how does the keyword word in C#? What is the internal implementation of the keyword in the C# compiler? Let’s understand. The method containing the yield keyword can be consumed by an iterator loop such as foreach or LINQ query. Each iteration of the loop makes a call to the method. The code in the method is executed until a yield return or yield break statement is encountered.
  2. The current position of the execution in the method is retained and the next iteration continues from where it left off in the previous iteration.
  3. This was simple, wasn’t it? Let’s get into the technical implementation of the same. The method containing the yield keyword must always return an IEnumerable or IEnumerator. Whenever the compiler encounters the yield keyword, it knows that the method is consumed by an iterator. When the method is called, the compiler doesn’t execute the method body as it normally does.
  4. Rather it executes the method body and returns a compiled set of IEnumerables to the consuming iterator variable. On every call of the method, the compiler looks for a yield statement and pauses the execution at that statement. The next iteration of the loop continues the execution from the last paused location. This goes on till the exit condition of the loop or a yield break statement. To store the state information after each iteration, the compiler creates a state machine.

Examples of Yield Keyword in C#

Let us consider some examples:

Example #1 – Method

The example below generates the Fibonacci series using the yield keyword.

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
foreach (int ele in GetFibonacciSeries(10))
{
Console.Write(ele + "\t");
}
}
public static IEnumerable<int> GetFibonacciSeries(int x)
{
for (int a = 0, b = 0, c = 1; a < x; a++)
{
yield return b;
int temp = b + c;
b = c;
c = temp;
}
}
}

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

Yield Keyword in C# 1

Example #2 – Accessor

The following example uses the yield keyword with a get accessor.

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
foreach (Day day in new Days().DaysOfWeek)
{
Console.WriteLine("Day {0} of the week is {1}", day.DayOfWeek, day.DayName);
}
}
public static IEnumerable<int> Show(int x)
{
for (int a = 0, b = 0, c = 1; a < x; a++)
{
yield return b;
int temp = b + c;
b = c;
c = temp;
}
}
public class Days
{
public IEnumerable<Day> DaysOfWeek
{
get
{
yield return new Day{DayName = "Sunday", DayOfWeek = 1};
yield return new Day{DayName = "Monday", DayOfWeek = 2};
yield return new Day{DayName = "Tuesday", DayOfWeek = 3};
yield return new Day{DayName = "Wednesday", DayOfWeek = 4};
yield return new Day{DayName = "Thursday", DayOfWeek = 5};
yield return new Day{DayName = "Friday", DayOfWeek = 6};
yield return new Day{DayName = "Saturday", DayOfWeek = 7};
}
}
}
public class Day
{
public string DayName
{ get; set; }
public int DayOfWeek
{ get; set; }
}
}

Yield Keyword in C# 2

Example #3 – yield break

The following example demonstrates the use of the yield break statement. The iteration is terminated as soon as a number in the series is found or the max search limit is reached.

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int elementToFind = 21;
int maxElements = 100;
foreach (int ele in FindFibonacciNumber(elementToFind, maxElements))
{
Console.Write("Found the number " + elementToFind + " in Fibonacci series.");
}
}
public static IEnumerable<int> FindFibonacciNumber(int n, int max)
{
for (int a = 0, b = 0, c = 1; true; a++)
{
if (a > max)
{
Console.Write("Searched first " + max + " Fibonacci numbers. Element " + n + " not found");
yield break;
}
if (b == n)
{
yield return b;
yield break;
}
int temp = b + c;
b = c;
c = temp;
}
}
}

Yield Keyword in C# 3

If we change elementToFind 1234, the output will be –

Yield Keyword in C# 4

Rules

1) Each element must be returned one at a time using the yield return statement.
2) The return type must be an IEnumerable or IEnumerator.
3) You cannot use it in, ref, or out keywords with yield.
4) Yield keyword cannot be used with Lambda Expressions or Anonymous Methods.
5) A yield return statement cannot be inside a try-catch block. It can be inside a try-finally block.
6) A yield break statement cannot be inside a try-finally block. It can be inside a try-catch block.

Advantages

The yield keyword spares the need to create temporary collections. You need not create temporary collections to store the data before it is returned from the method. Also, the execution state of the method is retained and thus need not be explicitly stored in the code.

Conclusion – Yield Keyword in C#

We learned from this article that how to yield keyword is a very useful keyword in C#. It helps code complex problems with as few lines as possible and also makes the code easy to understand. This was an advanced level article on the C# journey. It is recommended to try and use the keyword in your code so that you get some hands-on practice.

Recommended Articles

This is a guide to Yield Keyword in C#. Here we discuss How to yield keyword works in C# with Examples, Advantages, and Rules. You may also look at the following article to learn more –

  1. Overriding in C#
  2. Namespaces in C#
  3. Pointers in C#
  4. Destructor in C#

C# Training Program (6 Courses, 17 Projects)

6 Online Courses

17 Hands-on Project

89+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Training Program (6 Courses, 17 Projects) Learn More