Tuesday, 26 December 2017

What is the Use of Yield Keyword Or Reserved Word in C#.Net

Dear all In this article emphasize the need of yield keyword in C#.Net programming practices.In Deep dive of this here i elaborated following things



What is the use of Yield keyword in C#.Net ?
Where to use of Yield keyword in C#.Net ?
What is yield statement infer in C#.Net ?
How Yield Keyword Used in C#.Net ?

Defination:
              Yield is a key word which keep on produces it outcomes till the end of its source list.By this we can understood that it will applicable on iterators

Usage of Yield Keyword is :
              Yield keyword avoids unnecessary overheads in the type declarations by considering  explicit or temporary classes or variables Where We can use Keywords :

  1. We can make use in the methods
  2. We can use in the operator
  3. We can use in the get accessor 
How many Forms of Yield Exists

There were two forms of yield statement exists
yield return <expression>;
yield break;

Here I want to potriat an Example with usage of Yield Keyword



Here i want to consider a Generic List contains a class Named as TravelInfo

class TravelInfo
    {
        public long TicketNo { get; set; }
        public string PrimaryPassenger { get; set; }
        public double TotalAmount { get; set; }
    }

Scenario 1 :Fetch the data who's ticket Amount is greater than 500 rupees with Yield keyword

Steps to accomplish the yield keyword Scenario 1
1.Fill the object with the respective data

static List<TravelInfo> _Traveldata = new List<TravelInfo>();
_Traveldata.Add(new TravelInfo { TicketNo = 12345, PrimaryPassenger = "Veerendra", TotalAmount = 500.00d });
_Traveldata.Add(new TravelInfo { TicketNo = 6789, PrimaryPassenger = "Naga", TotalAmount = 1030d });
_Traveldata.Add(new TravelInfo { TicketNo = 101231, PrimaryPassenger = "Ram", TotalAmount = 5030d });

2.Fetch all the information without filter

foreach (var item in _Traveldata)
 {                                   Console.WriteLine(item.TicketNo+"\t"+item.PrimaryPassenger+"\t"+item.TotalAmount);
 }

3.Now apply the filter with the yield keyword

static IEnumerable<TravelInfo> FetchAbove500FareData()
        {
            foreach (TravelInfo t in _Traveldata)
            {
                if (t.TotalAmount > 500)
                    yield return t;
            }
        }

Complete Output : 

foreach (var item in FetchAbove500FareData())
            {
                Console.WriteLine(item.TicketNo+"\t"+item.PrimaryPassenger+"\t"+item.TotalAmount);
            }



Scenario 2 : Apply a yield keyword with primitive type iterator

Steps to accomplish the yield keyword Scenario 2
1.Fill the object with the respective data

static List<string> _Acronyms = new List<string>();
_Acronyms.Add("Network Enabled Technoloy");
_Acronyms.Add("Uniform Resource Identifier");
_Acronyms.Add("Asynchronous Java Script And XML");
_Acronyms.Add("Hyper Text Markup Language");
_Acronyms.Add("Extensible Markup Language");

2.Fetch all the information without filter

foreach (var item in _Acronyms)
{
   Console.WriteLine(item);
}

3.Now apply the filter with the yied keyword

static IEnumerable<string> FetchData()
        {
            foreach (var t in _Acronyms)
            {
                if (t.Length>20)
                    yield return t.Substring(0,20)+"...";
            }
        }

Complete Output : 

foreach (var item in FetchData())
 {
  Console.WriteLine(item);
 }

Complete Program : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YieldEx
{
    class P1
    {
        static List<TravelInfo> _Traveldata = new List<TravelInfo>();
        static List<string> _Acronyms = new List<string>();
        static void Main(string[] args)
        {
            _Traveldata.Add(new TravelInfo { TicketNo = 12345, PrimaryPassenger = "Veerendra", TotalAmount = 500.00d });
            _Traveldata.Add(new TravelInfo { TicketNo = 6789, PrimaryPassenger = "Naga", TotalAmount = 1030d });
            _Traveldata.Add(new TravelInfo { TicketNo = 101231, PrimaryPassenger = "Ram", TotalAmount = 5030d });
            _Acronyms.Add("Network Enabled Technoloy");
            _Acronyms.Add("Uniform Resource Identifier");
            _Acronyms.Add("Asynchronous Java Script And XML");
            _Acronyms.Add("Hyper Text Markup Language");
            _Acronyms.Add("Extensible Markup Language");

            Console.ForegroundColor = ConsoleColor.Yellow;

            Console.WriteLine("Total Travelling Data is : ");

            foreach (var item in _Traveldata)
            {
                Console.WriteLine(item.TicketNo+"\t"+item.PrimaryPassenger+"\t"+item.TotalAmount);
            }
            Console.ForegroundColor = ConsoleColor.Magenta;  
            Console.WriteLine("After Yield Filteration of Fetching Above 500 Ticket Holders Information ....");

            foreach (var item in FetchAbove500FareData())
            {
                Console.WriteLine(item.TicketNo+"\t"+item.PrimaryPassenger+"\t"+item.TotalAmount);
            }

            Console.WriteLine("**************************************");
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("All Acronyms....");
            foreach (var item in _Acronyms)
            {
                Console.WriteLine(item);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Applying Logic With the Yield Keyword ");
            foreach (var item in FetchData())
            {
                Console.WriteLine(item);
            }
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("Thank You for Visting PNV Technical Hub Blog @@@ www.seoVeerendra.blogspot.com");
            Console.ReadLine();
        }
        static IEnumerable<TravelInfo> FetchAbove500FareData()
        {
            foreach (TravelInfo t in _Traveldata)
            {
                if (t.TotalAmount > 500)
                    yield return t;
            }
        }
        static IEnumerable<string> FetchData()
        {
            foreach (var t in _Acronyms)
            {
                if (t.Length>20)
                    yield return t.Substring(0,20)+"...";
            }
        }
    }
    class TravelInfo
    {
        public long TicketNo { get; set; }
        public string PrimaryPassenger { get; set; }
        public double TotalAmount { get; set; }
    }
}



Output of the Program : 


Points To Remember : 

1.We can't apply Yield Keyword in List<string> return types but we can apply IEnumerable<string> or Iterator supportable items

2.Though Yield is a keyword even we can use it as a variable i.e.., int yield = 10.Here yield acts as a variable.It doesn't mean that it was a Keyword.Microsoft allows this generally it wont allows for majority keywords which means we can't use it as a variable

3.Performance wise yield takes more time than normal filteration.Advantage is Simplifies some programming scenarios

4.A yield return statement can't be located in a try-catch block. A yield return statement can be located in the try block of a try-finally statement.




No comments :

Post a Comment