Keyword of C# Use Lazy Evaluation

Published:

This essay has been submitted by a student. This is not an example of the work written by our professional essay writers.

How does Yield Keyword of C# Use Lazy Evaluation?

C# is a wonderful language providing useful and effective concepts during its every version release. Yield is one such concept introduced in C# Version 2.0 and effectively used along with iterators. When you deal with functional programming, evaluation of code can be classified as eager evaluation and lazy evaluation. If you didn't get a chance to know about them so far, then this article gives you the chance to know about them and in addition learn how to implement them in C#.

Evaluation in code perspective means the execution of your code. Assume that you are accessing list of items in a sequence, how do you fetch those items into memory?

  • If you fetch all of those items together and store the entire list in memory, then you are using eager evaluation
  • If you fetch only one item at a time from the list, store it in memory, process it and then you fetch and store the next item in memory, in this case you are using lazy evaluation

Think about the codes that you have written so far... how many times do you think you have implemented lazy evaluation? Most of your answer will be... not even once. Most of you will be using only early evaluation. For example, you have to fetch records from customer table of the database based on specific criteria. Assume that there are 10000 matching records. What will you do? You write a query and fetch all 10000 matching records and store them in memory. This is eager evaluation. As a developer, you receive the required output and you don't bother much. But think about the memory consumption. Even if you have 10000 records, you are going to access only one record at a time. Then why do you have to store the whole lot in memory? What if you get an option to fetch and store the first matching customer record in memory, process it and then search for the next record? This will increase performance of your code and improvise your memory management too. This option is nothing but lazy evaluation and it is accomplished using the contextual keyword called yield in C#.

Not just memory management, sometimes you cannot go with eager evaluation and you will be forced to use lazy evaluation. Here is one such scenario: You want to display all even numbers. How do you do it? Here is the code sample:

public class sampleClass {

static void getEvenNumber() {

int number=1;

Console.Write("List of even numbers are:");

while(true) {

if(number%2 == 0) {

Console.Write(number+",");

evenNumbers.Add(number);

}

number++;

}

}

public static void Main() {

  getEvenNumber();

}

}

Output of the code will be:

List of even numbers are:2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,...

When you execute the code, what happens? Execution will go on in an infinite way and it will never terminate. Why? Because you have not specified the limit till which the even number generation has to happen. This is a code sample for eager evaluation. You try to fetch the entire result of even numbers in one go. Even if you go for lazy evaluation when you don't specify the limit in getEvenNumber() method, will the execution terminate? Yes it will. The equivalent code of the above scenario using lazy evaluation will be:

public class sampleClass {

static

IEnumerable<int>

getEvenNumber() {

int number=1;

while(true) {

if(number%2 == 0) {

yield return number;

}

number++;

}

}

public static void Main() {

IEnumerable<int> evenNos = getEvenNumber();

IEnumerator<int> enumEven = evenNos.GetEnumerator();

Console.Write("List of even numbers are:");

for(int index=0; index<5;index++) {

enumEven.MoveNext();

Console.Write(enumEven.Current+",");

 }

}

}

Output of this code will be:

List of even numbers are: 2,4,6,8,10

The execution is terminated and you get a finite result. How is this possible? Consider the modified code above. There are just two changes in getEvenNumber() method when compared to the earlier version:

  • Return type of getEvenNumber() is changed as IEnumerable<int>
  • When the even number condition check is satisfied, you return the number. Yield keyword is associated before the return keyword.
  • Yield keyword will return only one number at a time. The next number will be processed only when the next iteration happens. Though you have not set a limit for even number generation in getEvenNumber() method, the control key is in Main() method. Compare the Main() method in above two examples. It is completely different. In the eager evaluation, you just call the getEvenNumber() method. But in lazy evaluation, you do more than that. You use the property and method of IEnumerator interface. All that you do in Main() method is listed below:

  • You assign the call of getEvenNumber() method to IEnumerable<int>
  • You create an enumerator named enumEven to iterate getEvenNumber() using evenNos.GetEnumerator(). GetEnumerator() is the default method triggered by the iterator or enumerator.
  • You then repeat the following tasks 5 times:
  • Use MoveNext() method of IEnumerator interface to progress to the next iteration
  • Use Current property of IEnumerator interface to fetch the value of the current iteration

To make it more clear, when enumEven.MoveNext() statement is triggered, getEvenNumber() is called until yield statement is encountered. Then control comes to the next line in for loop:

Console.Write(enumEven.Current+",");

enumEven.Current will fetch the value returned by yield return number; statement in getEvenNumber() method. Since you have iterated the for loop 5 times, the yield statement is executed 5 times and the execution stops even it getEvenNumber() method doesn't have any termination point. Hence the output values are 2,4,6,8,10.

References

:

http://msdn.microsoft.com

http://mariusbancila.ro/blog

http://blogs.msdn.com

http://stackoverflow.com

Writing Services

Essay Writing
Service

Find out how the very best essay writing service can help you accomplish more and achieve higher marks today.

Assignment Writing Service

From complicated assignments to tricky tasks, our experts can tackle virtually any question thrown at them.

Dissertation Writing Service

A dissertation (also known as a thesis or research project) is probably the most important piece of work for any student! From full dissertations to individual chapters, we’re on hand to support you.

Coursework Writing Service

Our expert qualified writers can help you get your coursework right first time, every time.

Dissertation Proposal Service

The first step to completing a dissertation is to create a proposal that talks about what you wish to do. Our experts can design suitable methodologies - perfect to help you get started with a dissertation.

Report Writing
Service

Reports for any audience. Perfectly structured, professionally written, and tailored to suit your exact requirements.

Essay Skeleton Answer Service

If you’re just looking for some help to get started on an essay, our outline service provides you with a perfect essay plan.

Marking & Proofreading Service

Not sure if your work is hitting the mark? Struggling to get feedback from your lecturer? Our premium marking service was created just for you - get the feedback you deserve now.

Exam Revision
Service

Exams can be one of the most stressful experiences you’ll ever have! Revision is key, and we’re here to help. With custom created revision notes and exam answers, you’ll never feel underprepared again.