Saturday, 3 September 2016

Extension Methods

Extension Methods

Open Closed Principle(OCP) states that we should design our types in such a way that it should be open for extension but closed for modification. Extension methods in C# can be thought of as a mechanism to implement the OCP for user defined types or even the primitive types and the types defined in the framework.
Extension methods allow us to extend an existing type by adding additional methods and functionality to an existing type without needing to change the code of that type(we might even not have code in most cases). Prior to the existence of extension methods, developers used to create their own types and either inherit or contain the existing type inside these types. These new types were more of the wrappers on the existing types rather than the actual extensions of these types.
For example  if we needed to have the functionality of getting the negative of an integer then I will have to wrap my integer in a custom type and then use this custom type to perform the operation.
// Old way of extending using wrapper classes
struct MyInt
{
    int value;       
 
    public MyInt(int val)
    {
        this.value = val;
    }
 
    public int Negate()
    {
        return -value;
    }
}
 
static void Main(string[] args)
{
    // Old way of using wrappers for extensions
    MyInt i = new MyInt(53);
    Console.WriteLine(i.Negate());
}
Now this approach did work but the problem is that we are not at all extending the existing type. We are creating a new type all together that is wrapping the existing type and then providing us the desired functionality.
So if we really want to extend a method we should be able to add this method Negate in the int type only and everyone should be able to call this method on int type only. No need to create another type to have this additional functionality. Extension methods provides just the same thing. Using extension methods we can write the custom functionality and can hook them with the existing types so that they can be used on those types.
To create an extension method, we need to take the following steps:
1.     Define a static class.
2.     Define a public static function in this class with the name desired as the mew method name and return value as per the functionality.
3.     Pass the parameter of type that you want to extend. The important thing here is to put a this keyword before the parameter to tell the compiler that we need to extend this type and we are not really expecting this type as argument.
So lets try to add this Negate function in the int type.

Extension Methods

Open Closed Principle(OCP) states that we should design our types in such a way that it should be open for extension but closed for modification. Extension methods in C# can be thought of as a mechanism to implement the OCP for user defined types or even the primitive types and the types defined in the framework.
Extension methods allow us to extend an existing type by adding additional methods and functionality to an existing type without needing to change the code of that type(we might even not have code in most cases). Prior to the existence of extension methods, developers used to create their own types and either inherit or contain the existing type inside these types. These new types were more of the wrappers on the existing types rather than the actual extensions of these types.
For example  if we needed to have the functionality of getting the negative of an integer then I will have to wrap my integer in a custom type and then use this custom type to perform the operation.
Hide   Copy Code
// Old way of extending using wrapper classes
struct MyInt
{
    int value;       
 
    public MyInt(int val)
    {
        this.value = val;
    }
 
    public int Negate()
    {
        return -value;
    }
}
 
static void Main(string[] args)
{
    // Old way of using wrappers for extensions
    MyInt i = new MyInt(53);
    Console.WriteLine(i.Negate());
}
Now this approach did work but the problem is that we are not at all extending the existing type. We are creating a new type all together that is wrapping the existing type and then providing us the desired functionality.
So if we really want to extend a method we should be able to add this method Negate in the int type only and everyone should be able to call this method on int type only. No need to create another type to have this additional functionality. Extension methods provides just the same thing. Using extension methods we can write the custom functionality and can hook them with the existing types so that they can be used on those types.
To create an extension method, we need to take the following steps:
1.     Define a static class.
2.     Define a public static function in this class with the name desired as the mew method name and return value as per the functionality.
3.     Pass the parameter of type that you want to extend. The important thing here is to put a this keyword before the parameter to tell the compiler that we need to extend this type and we are not really expecting this type as argument.
So lets try to add this Negate function in the int type.
Hide   Copy Code
// Extending using Extension methods
static class MyExtensionMethods
{
    public static int Negate(this int value)
    {
        return -value;
    }
}
 
static void Main(string[] args)
{
    //Using extension method
    int i2 = 53;
    Console.WriteLine(i.Negate());
}
Now using extension method let us define the methods on some existing type. Now what if we want the new method to accept some parameters. Well to do this we can define additional parameters after the first parameter that is of the type to be extended (used with this keyword . Let define one more function in int calledMultiply to see this in action.
Hide   Copy Code
// Extending using Extension methods
static class MyExtensionMethods
{
    public static int Negate(this int value)
    {
        return -value;
    }
 
    public static int Multiply(this int value, int multiplier)
    {
        return value * multiplier;
    }
}
 
static void Main(string[] args)
{
    // Passing arguments in extension methods
    int i3 = 10;
    Console.WriteLine("Passing arguments in extension methods: {0}", i3.Multiply(2));
}
Now there are two points that need to be remembered before implementing extension methods.
·         First of which is that the extension methods can only access the public properties of the type.
·         The extension method signature should not be same as an existing method of the type.
·         The extension method for a type can only be used if the namespace that contains the extension method is in scope.
·         In case we define extension methods in such a way that it overloads an existing method of the original type and the calls are getting ambiguous then the overload resolution rule will always choose the instance method over the extension method.
·         If there is some ambiguity between two extension methods then the method containing more specific arguments will get called.
If we keep the following point in mind we could really utilize the extension methods to better design and extend the types and provide better abstraction of the type. LINQ uses extension methods heavily. It is highly recommended to look at how LINQ used extension methods in conjunction with LAMBDA expression.
// Extending using Extension methods
static class MyExtensionMethods
{
    public static int Negate(this int value)
    {
        return -value;
    }
}
 
static void Main(string[] args)
{
    //Using extension method
    int i2 = 53;
    Console.WriteLine(i.Negate());
}
Now using extension method let us define the methods on some existing type. Now what if we want the new method to accept some parameters. Well to do this we can define additional parameters after the first parameter that is of the type to be extended (used with this keyword . Let define one more function in int calledMultiply to see this in action.
// Extending using Extension methods
static class MyExtensionMethods
{
    public static int Negate(this int value)
    {
        return -value;
    }
 
    public static int Multiply(this int value, int multiplier)
    {
        return value * multiplier;
    }
}
 
static void Main(string[] args)
{
    // Passing arguments in extension methods
    int i3 = 10;
    Console.WriteLine("Passing arguments in extension methods: {0}", i3.Multiply(2));
}
Now there are two points that need to be remembered before implementing extension methods.
·         First of which is that the extension methods can only access the public properties of the type.
·         The extension method signature should not be same as an existing method of the type.
·         The extension method for a type can only be used if the namespace that contains the extension method is in scope.
·         In case we define extension methods in such a way that it overloads an existing method of the original type and the calls are getting ambiguous then the overload resolution rule will always choose the instance method over the extension method.
·         If there is some ambiguity between two extension methods then the method containing more specific arguments will get called.
If we keep the following point in mind we could really utilize the extension methods to better design and extend the types and provide better abstraction of the type. LINQ uses extension methods heavily. It is highly recommended to look at how LINQ used extension methods in conjunction with LAMBDA expression.


Friday, 2 September 2016

Predicate in C#

Predicate. A Predicate returns true or false. The Predicate type in the C# language stores a method that receives one parameter and returns one value of true or false. And it is often used with lambda expression syntax.
True, False

Example. We look at a program that uses two Predicate instances with the parameterized type of integer. The return value of Predicate types is always bool (true or false). The Predicate types are assigned to lambda expressions.
Then:
The program then demonstrates how the Invoke method always returns true or false when it is called in the source text.





C# program that uses Predicate type instances

using System;

class Program
{
    static void Main()
    {
//
// This Predicate instance returns true if the argument is one.
//
Predicate<int> isOne =
   x => x == 1;
//
// This Predicate returns true if the argument is greater than 4.
//
Predicate<int> isGreaterEqualFive =
   (int x) => x >= 5;

//
// Test the Predicate instances with various parameters.
//
Console.WriteLine(isOne.Invoke(1));
Console.WriteLine(isOne.Invoke(2));
Console.WriteLine(isGreaterEqualFive.Invoke(3));
Console.WriteLine(isGreaterEqualFive.Invoke(10));
    }
}

Output

True
False
False
True

In this example, the lambda expression syntax is used to specify the function body for the Predicates. The => syntax separates the arguments from the method bodies. The right-hand side is evaluated to a Boolean result.
In lambda expressions, the right-hand side of the expression acquires an implicit return value if this is indicated by the context. The Predicate type must always have a Boolean return value.
Note:
The two above lambdas return true if the argument is one, and if the argument is greater than four.
Finally:
The program executes the Invoke instance method on the Predicate types to demonstrate the functionality.

List. Predicate is often used with the List generic type. You can specify a lambda expression as the argument to certain List methods. The C# compiler then uses type inference to resolve the lambda expression to the correct Predicate type.
Note:
You can store the Predicate in a field or local variable. Please see the articles on the Find and RemoveAll methods for details.
RemoveAll
Find

Concept. The concept of predicate functions is explored in the book Structure and Interpretation of
Computer Programs. In the book, predicates are described as functions that must return true or false.
This is the meaning of the term predicate when describing functions. The type Predicate in the .NET Framework adheres to this definition, but is just a specific implementation of the concept.
Summary. We looked at the Predicate type. We saw how it is applied correctly to lambda expressions where the result value is of type bool. The method body on the right-hand side of a lambda expression is evaluated in a boolean context.
And:
The term predicate, as a method returning true or false, has wide applicability in computer science.

Yield Keyword

“Yield keyword helps us to do custom stateful iteration over .NET collections.”
There are two scenarios where “yield” keyword is useful:-
·         Customized iteration through a collection without creating a temporary collection.
·          Stateful iteration.

Scenario 1:- Customized iteration through a collection
Let’s try to understand what customized iteration means with an example. Consider the below code.
Let say we have a simple list called as “MyList” which has collection of 5 continuous numeric values 1,2,3,4 and 5. This list is browsed/iterated from console application from within static void main method.
For now let’s visualize the “main()” method as a caller. So the caller i.e. “main()” method calls the list and displays the items inside it. Simple…till now 
static List<int> MyList = new List<int>();
 
static void FillValues()
{
            MyList.Add(1);
            MyList.Add(2);
            MyList.Add(3);
            MyList.Add(4);
            MyList.Add(5);
}
static void Main(string[] args) // Caller
{
            FillValues(); // Fills the list with 5 values
            foreach (int i in MyList) // Browses through the list
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
}

Now let me complicate this situation let’s say the caller only wants values greater than “3” from the collection. So the obvious thing as a c# developer we will do is create a function as shown below. This function will have temporary collection. In this temporary collection we will first add values which are greater than “3” and return the same to the caller. The caller can then iterate through this collection.
static IEnumerable<int> FilterWithoutYield()
 
{
            List<int> temp = new List<int>();
            foreach (int i in MyList)
            {
                if (i > 3)
                {
                    temp.Add(i);
                }
            }
            return temp;
} 



Now the above approach is fine but it would be great if we would get rid of the collection, so that our code becomes simple. This where “yield” keyword comes to help. Below is a simple code how we have used yield.
“Yield” keyword will return back the control to the caller, the caller will do his work and re-enter the function from where he had left and continue iteration from that point onwards. In other words “yield” keyword moves control of the program to and fro between caller and the collection.
static IEnumerable<int> FilterWithYield()
 
{
            foreach (int i in MyList)
            {
                if (i > 3) yield return i;
            }
}  
So for the above code following are details steps how the control will flow between caller and collection. You can also see the pictorial representation in the next diagram shown below.
·         Step 1:- Caller calls the function to iterate for number’s greater than 3.
·         Step 2:- Inside the function the for loop runs from 1 to 2 , from 2 to 3 until it encounters value greater than “3” i.e. “4”. As soon as the condition of value greater than 3 is met the “yield” keyword sends this data back to the caller.
·         Step 3:- Caller displays the value on the console and re-enters the function for more data. This time when it reenters, it does not start from first. It remembers the state and starts from “5”. The iteration continues further as usual.


Scenario 2:- Stateful iteration
Now let us add more complications to the above scenario. Let’s say we want to display running total of the above collection. What do I mean?.

In other words we will browse from 1 to 5 and as we browse we would keep adding the total in variable. So we start with “1” the running total is “1”, we move to value “2” the running total is previous value “1” plus current value “2” i.e. “3” and so on.
Below is the pictorial representation of the running total looks like.


In other words we would like to iterate through the collection and as we iterate would like to maintain running total state and return the value to the caller ( i.e. console application). So the function now becomes something as shown below. The “runningtotal” variable will have the old value every time the caller re-enters the function.
static IEnumerable<int> RunningTotal()
         {
             int runningtotal=0;
             foreach(int i in MyList)
             {
                  runningtotal += i;
                 yield return (runningtotal);
                 
             }
         }
Below goes the caller code and output.
Hide   Copy Code
foreach (int i in RunningTotal())
 
            {
                Console.WriteLine(i);
            } 
            Console.ReadLine(); 



Practical use of Func

What is Func?
Func in short is parameterized delegate. In C#, a delegate instance points towards a method. When a caller invokes the delegate, it calls its target method. This way, the caller is not invoking the target method rather invoking the delegate which can call the target method. We do it because it creates an abstraction on invoking the target method. We of course always can invoke a method directly but decoupling of the client and target method is sometimes a need or gives us more flexibility to make things clean and simple.
We can use Func delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate.
Why I said it's a parameterized delegate:
delegate TResult Func <out TResult> ();
delegate TResult Func <in T, out TResult> (T arg);

delegate TResult Func <in T1, in T2, out TResult> (T1 arg1, T2 arg2);

... and so on, up to T16  
The Problem
To understand use of Func, we must understand what problems it can solve. Let's say we have an int array here.
IEnumerable<int> numbers = new[] {3, 4, 7, 1, 8, 10, 21, 5, 9, 11, 14, 19};
It's a simple array. If we want to print the numbers which are greater than 10, we will write a method like below. We will send the array as parameter and will get another array which will contain the numbers that are greater than 10.
public IEnumerable<int> GetGreaterThanTen(IEnumerable<int> numbers)
{
    foreach (int number in numbers)
        if (number > 10)
            yield return number;
}
…and then if we want to print the numbers which will have result less than 1 after divided by 5, we will write a method:
public IEnumerable<int> GetGreterThanOneAfterDevidedByFive(IEnumerable<int> numbers)
{
    foreach (int number in numbers)
        if ((number/5) > 1)
            yield return number;
}
The Solution
In the above way, we will add more methods as the new conditions come. But there is a better way to face this problem. We can and should use delegate to avoid rewriting a fresh method every time we get by a new rule we want to apply for this array. Use of Func as method parameter we will have the leverage to decouple the caller and the function we want to use. Func will pass the rule to the method body and will apply it.
Hide   Copy Code
public IEnumerable<int> GetNumbers(IEnumerable<int> numbers, Func<int, bool> numberResolver)
{
    foreach (int number in numbers)
        if (numberResolver(number))
            yield return number;
}
IEnumerable<int> numbers = new[] {3, 4, 7, 1, 8, 10, 21, 5, 9, 11, 14, 19};

IEnumerable<int> greaterThanTen = GetNumbers(numbers, x=>x>10);
greaterThanTen.ToList().ForEach(Console.WriteLine);

Console.WriteLine("\n");

IEnumerable<int> greaterThanOneAfterDividedByFive = GetNumbers(numbers, n => (n/5) > 1);
greaterThanOneAfterDividedByFive.ToList().ForEach(Console.WriteLine);
The above code is pretty self-explanatory. Func uses Lambda expression which is essentially an anonymous function.
For extensibility standpoint, Func is very effective. While writing various extension methods, you will find it extremely useful.
Getting TResult
The x-factor of Func is probably Func<TResult>. For functional programming, the return type has great use. For example:
Hide   Copy Code
Func<int, int> square = num => num*num;
Console.WriteLine(square(3));
…also, we can bring the previous example here see a bit more complex scenario.
Hide   Copy Code
IEnumerable<int> numbers = new[] { 3, 4, 7, 1, 8, 10, 21, 5, 9, 11, 14, 19 };
Func<IEnumerable<int>, IEnumerable<int>> getGreaterThanTen = nums =>
{
    var array = new List<int>();
    nums.ToList().ForEach(x =>
    {
        if (x > 10)
            array.Add(x);
    });
    return array;
};

var result = getGreaterThanTen(numbers);

result.ToList().ForEach(Console.WriteLine);