Generic Extension Methods

Extension methods are used across .NET library more often than not, Let’s see through below example

using System;
using System.Collections.Generic;
using System.Text;
class Program
{        
     static void Main(string[] args)
     {
         IEnumerable list = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
         list.
     }
}

When we dot there are only five methods you can see an images, where are other methods like select, count, sum etc….
See below visual reference

Step1
Food For Thought
First of let me clear all these methods are extension methods of IEnumerable to use these methods we need Enumerable under System.Linq namespace contains all extension methods, See below visual reference of Enumerable class much like utility class
Step2

Just add using System.Linq; will include all necessary extension methods see below , can be seen arrow going bottom against  methods indicating extension methods
Step3

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace LinqToSql
{
    class Program
    {        
        static void Main(string[] args)
        {
            IEnumerable list = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            list.Sum();
        }
    }    
}

Last but not the least below is complete example to create new generic extension method of IENumerable

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace LinqToSql
{
    /// Extension Or Utility Class 
    public static class Enumerable
    {
        /// Syntax For Extenstion Method
        /// static Type MehodeName(this Type)
        public static IEnumerable NumberFilter(this IEnumerable list, Predicate condition)
        {
            foreach (var item in list)
            {
                if (condition(item))
                {
                    yield return item;
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable list = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            /// NumberFilter Available Without Doing Much
            IEnumerable filterEven = list.NumberFilter(x => x % 2 == 0);
            foreach (var item in filterEven)
            {
                Console.WriteLine("Even Number:{0}", item);
            }
            IEnumerable filterOld = list.NumberFilter(x => x % 2 != 0);
            foreach (var item in filterEven)
            {
                Console.WriteLine("Odd Number:{0}", item);
            }
        }
    }
}

Visual Reference For New Generic Extension Method

Step4

Powershell Interesting String Operations / Work Around

<########## Work around to remove string with Case In Sensitive Approach ##########>

$full_string = "My name is xyz !!!"
$rm_string = ''
if($full_string -match "XyZ") {
   $index = $full_string.indexof($matches[0])
   if($index -gt 0) {
      $rm_string = $full_string.remove($index)      
   }
}
write-host $rm_string
#Note: I like one liner solution if anybody has

Output:
Case-Sensitive Is Ignored !!!

<######## StartWith Function With Case In Sensitive ########>

$test = "Start word of string"
if($test.StartsWith("stArT","CurrentCultureIgnoreCase") ) {
    Write-Output "Case-Sensitive Is Ignored !!!"
}

Output:
Case-Sensitive Is Ignored !!!

<######## Difference Split String By Word & Character ########>

$test = "Start//word/of/string"

Write-Output "------------------"
Write-Output "Split By Character"
Write-Output "------------------"
$test.split('/') |% {
    Write-Output $_
}

Write-Output "------------------"
Write-Output "Split By Word"
Write-Output "------------------"
$test -split "//" |% {
    Write-Output $_
}

Output:
------------------
Split By Character
------------------
Start

word
of
string
------------------
Split By Word
------------------
Start
word/of/string

<######## Compare Multiple Words In String ########>

$test = ("1 2", "2 3", "1 5", "3 4")
$test |% {
    if($_ -match "3|4") {
        Write-Output $_
    }
}

Output:
2 3
3 4

Greedy Operators For Eager, Not For Lazy !!!

——————————————————-
Deferred execution or Lazy execution
——————————————————-

We have seen how YIELD keyword works

One of the fundamental use of it deferred execution or lazy execution of code
We try to see this practically

class Program
{        
   static void Main(string[] args)
   {
      IEnumerable EvenNum = Extension.GetEvenNumbers();
      foreach (var item in EvenNum)
      {
          Console.WriteLine("Selected Number: {0}", item);
      }            
   }
}

public static class Extension
{
   public static IEnumerable GetEvenNumbers()
   {
      IEnumerable list = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
      foreach (var item in list)
      {
          if (item % 2 == 0)
          {
              Console.WriteLine("Start Deferred Execution");
              yield return item;
              Console.WriteLine("Stop Deferred Execution");
          }
      }
   }
}

////// OUTPUT ///////
Start Deferred Execution
Selected Number: 2
Stop Deferred Execution
Start Deferred Execution
Selected Number: 4
Stop Deferred Execution
Start Deferred Execution
Selected Number: 6
Stop Deferred Execution
Start Deferred Execution
Selected Number: 8
Stop Deferred Execution
Press any key to continue . . .

It can be seen that due to yield return in GetEvenNumbers function is not called
unless we actually required return data from function, and to do so we need to
iterate using foreach

Food For Thought:
Useful to avoid unnecessary function call which are not actually used in system by developer (:D)

—————————————————
Eager Evaluation or Execution
—————————————————

Using Greedy Operators
ToList, ToArray, ToDictionary

Product A Concrete Type
Sum, First, Single, Count

The ToList() is also eager because it transforms a collection into a concrete IEnumerable

public static List ToList(this IEnumerable source)
{
    // Arguments checking is ommitted. 
    return new List(source);
}

Inside the constructor of List, the source is iterated, and all items are calculated
and added to the List collection before it is returned.

Append ToList and this function is executed immediately

IEnumerable EvenNum = Extension.GetEvenNumbers().ToList();

/////// OUTPUT /////////
Start Deferred Execution
Stop Deferred Execution
Start Deferred Execution
Stop Deferred Execution
Start Deferred Execution
Stop Deferred Execution
Start Deferred Execution
Stop Deferred Execution
Selected Number: 2
Selected Number: 4
Selected Number: 6
Selected Number: 8

Yield Is Fundamental For Lazy/Deffered execution

Let’s understand the problem using Client and Server classes

class Server
{        
   Random r = new Random();
   public void IterateNumber()
   {
      List integerList = Enumerable.Range(1,1000).ToList();
      foreach (var item in integerList)
      {
          int ProcessedNumber = ApplyProcess(item);
          Console.WriteLine("Process Number:{0}", ProcessedNumber );
      }                    
   }
   public int ApplyProcess(int num)
   {      
      r.Next(1, 10);
      return num * r.Next(1, 10);
   }
}

class Client
{
   Server serv = new Server();
   public void Execute()
   {
      serv.IterateNumber();
   }
}

Food For Thought

Server class processes each number nothing bad in that, but can client evaluate processed number and decide to stop at certain value

Does Client class has right to do that ???  To answer this question “YES”,  Yield  Keyword comes into the picture

In simple words yield return hold further iteration and return value to client to make decision to iterate further or not

class Server
{
   Random r = new Random();
   public IEnumerable IterateNumber()
   {
      List integerList = Enumerable.Range(1,1000).ToList();
      foreach (var item in integerList)
      {
          int ProcessedNumber = ApplyProcess(item);
          Console.WriteLine("Process Number:{0}", ProcessedNumber );
          yield return ProcessedNumber;
      }                    
   }
   public int ApplyProcess(int num)
   {            
      r.Next(1, 10);
      return num * r.Next(1, 10);
   }
}

class Client
{
   Server serv = new Server();
   public void Execute()
   {
      IEnumerable ienum = serv.IterateNumber();
      foreach (var item in ienum)
      {
          if ((int)item == 100)
          {
              break;
          }
      }
   }
}

Multiple Interface With Same Defination Name

Two different interface have same method name and only return type is different from one and otther

Consider a class derives both interfaces and want to call interface specific method

we start with simple example

First Step: A two interfaces with same method name and different return type

///// DEFINE INTERFACES /////
   interface One
   {
     int get();
   }
   interface Two
   {
     void get();
   }

Second Step: Implement Both Interfaces

 class Common : One,Two
   {
     int a = 10;
     public void get()
     {
         a = 12;
     }
     int One.get()
     {
         return a;
     }
   }

Third Step: Call Interface Specific Function

class Program
   {
     static void testing1(dynamic one)
     {
         Console.WriteLine(one);
     }
     static void Main(string[] args)
     {
         Common OBJ = new Common();
         OBJ.get();
         Console.WriteLine(((One)OBJ).get()); 
      }
   }