Search This Blog

Thursday, June 20, 2019

Generics

Generics allow us to design classes and methods decoupled from the data type.
Name Space: System.Collections.Generic

Example: Generic Method

using System;

namespace CSharpPracktice
{
    public class Generics
    {
        public bool AreEqual<Type>(Type value1, Type value2)
        {
            return value1.Equals(value2);
        }
       
    }

    public class GenericsCaller
    {
        public void Demo()
        {
            Generics generics = new Generics();
            bool result = generics.AreEqual<string>("20", "20");

            if (result)
                Console.WriteLine("Equal");
            else
                Console.WriteLine("Not Equal");
        }
    }
}

Example: Generic Class

using System;

namespace CSharpPracktice
{
    public class Generics<Type>
    {
        public bool AreEqual(Type value1, Type value2)
        {
            return value1.Equals(value2);
        }
       
    }

    public class GenericsCaller
    {
        public void Demo()
        {
            Generics<string> generics = new Generics<string>();
            bool result = generics.AreEqual("20", "20");

            if (result)
                Console.WriteLine("Equal");
            else
                Console.WriteLine("Not Equal");
        }
    }
}

Friday, June 14, 2019

Publish Subscriber Pattern

Publish Subscriber Pattern (Observer Design Pattern)

  • The Publisher/Subscriber pattern is one of the variations of the Observer designer pattern
  • A publisher publishes a message and there are one or more Subscribers who capture the published message.
  • Publishers broadcast messages, with no knowledge of the subscribers.
  • Subscribers ‘listen’ out for messages regarding topic/categories that they are interested in without any knowledge of who the publishers are.
  • The event bus transfers the messages from the publishers to the subscribers.
  • Each subscriber only receives a subset of the messages that have been sent by the publisher, they only receive the message topics or categories they have subscribed to.

Event Bus knows what topic each subscriber is subscribed to. The event bus will filter messages based on topic and send the messages to subscribers that are subscribed to the topic of the message. The publishers are responsible for defining the topics of their messages.



To understand this consider a real-life scenario where Mobile operators are sending messages to their customers.
 

Thursday, June 13, 2019

Callback

Callback: (Opposite to synchronous process)

Function that will be called when a process is done executing a specific task.
Usage is usually in asynchronous logic.

Example in simple term

Synchronous Process:

Customer go to shopkeeper and order to customize a boot. Shopkeeper takes some time to customize it and rerun it back to the customer. Customer wait till the process and when customer get back the customized shoes it gifted to his neighbor. This complete process is the simple example of synchronous process as customer has to wait till the process of shoe customization not done by the shopkeeper.

Asynchronous Process (Callback):

Customer go to shopkeeper and order to customize a boot. Shopkeeper told to the customer that it will takes some time to customize it. Customer said that I do not want to wait for the process. Take your time and when process for customization will be done then please handover the shoes to my neighbor, I do not want to wait for the process to accomplished. Shopkeeper said OK sure. Customer go back. Shopkeeper customized the shoe which takes some time and once done shopkeeper handover the shoes to the neighbor. This process is the example of asynchronous process as customer do not have to wait till the process was executing and this is also example of callback as once process of customization has been done, shoes was handover to the neighbor by the shopkeeper, which was to be done by customer in the synchronized process.

Example:


    public class CallbackDemo1
    {
        public delegate void DelegateSumOfNumbers(int x);

        public void PrintSumOfNumbers(int num)
        {
            Console.WriteLine("Sum of numbers is " + num);
        }

        public void Demo()
        {
            int num = 5;

            DelegateSumOfNumbers callBackSum = new DelegateSumOfNumbers(PrintSumOfNumbers);
            InnerClassForSum innerClassForSum = new InnerClassForSum(num, callBackSum);

            innerClassForSum.computeSum();
        }

        public class InnerClassForSum
        {
            private int number;
            private DelegateSumOfNumbers _callBackSum;
            public InnerClassForSum(int num, DelegateSumOfNumbers callBackSum)
            {
                number = num;
                _callBackSum = callBackSum;
            }
            public void computeSum()
            {
                int sum = 0;
                for (int i = 0; i <= number; i++)
                {
                    sum += i;
                }

                _callBackSum(sum);
            }
        }
    }

Wednesday, June 12, 2019

Delegate

Prerequisite:

  1. Type Safe: Can not move one data type to other data type. Type safety means preventing type errors. Type error happens when unknowingly developer assigns one data type to other causing bugs. In C# you can not assign one type value to another type value. C# is type safe, JavaScript is not type safe.
  2. Conversion: Converts from one data type to other data type using the convert class.
  3. Casting: Converts from one data type to other data type by defining the data type.
  4. Implicit Casting: No need to define to cast from where to where. No data loss.
  5. Explicit Casting: Need to define to cast from where to where. Data loss can happen.
  6. Reference Type: Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored. In other words, a reference type contains a pointer to another memory location that holds the data.
Delegate:

  • Type safe function pointer.
  • Just like class and string, Delegate is also reference type.
  • Representative for the communication between two parties.
  • Real world use is to callback and do the data communication.


Example-1:

 public class DelegateDemo
    {

        public delegate void DelegateName1();
        public delegate int DelegateName2();
        public delegate bool DelegateName3();
        public delegate bool DelegateName4(int x);

        public void method1()
        {
            Console.WriteLine("Method1 called.");
        }

        public int method2()
        {
            Console.WriteLine("Method2 called.");
            return 0;
        }

        private bool method3()
        {
            Console.WriteLine("Method3 called.");
            return false;
        }

        private bool method4(int x)
        {
            Console.WriteLine("Method4 called.");
            return false;
        }

        public void method5()
        {
            Console.WriteLine("Method5 called.");
        }

        public void Demo()
        {
            // calling methods directly
            method1();
            method2();
            method3();
            method5();

            // calling methods using reference i.e. delegate
            Console.WriteLine("Calling from delegate");
            DelegateName1 delegateName1 = new DelegateName1(method1);
            delegateName1();
            delegateName1.Invoke();

            delegateName1 += method5;
            delegateName1();

            DelegateName2 delegateName2 = new DelegateName2(method2);
            DelegateName3 delegateName3 = new DelegateName3(method3);
            DelegateName4 delegateName4 = new DelegateName4(method4);

            delegateName2();
            delegateName3();
            delegateName4(0);
        }

    }

Output:



Example-2:

Business Class

public class DelegateDemoBusinessClass
    {
        public delegate void DelGetCalculatedValue(int x, int y);

        private int _x, _y;
        private DelGetCalculatedValue _delegateObject;// = new DelGetCalculatedValue(getCalculatedValue);

        public DelegateDemoBusinessClass(int x, int y, DelGetCalculatedValue getCalculatedValue)
        {
            _x = x;
            _y = y;
            _delegateObject = this.getCalculatedValue;
        }
        public void getCalculatedValue(int x, int y)
        {
            _delegateObject(x, y);
        }
    }

User (Caller) Class

public class DelegateDemoCallerClass
    {
        enum typeOperation { Addition = 0, Substraction = 1, Multiplication = 2, Division = 3 };
        public static void Demo()
        {
            int x = 20, y = 10, operationChoice = 3;
            DelegateDemoBusinessClass.DelGetCalculatedValue getCalculated;

            if (operationChoice == Convert.ToInt32(typeOperation.Addition))
            {
                getCalculated = myAdd;
            }
            else if (operationChoice == Convert.ToInt32(typeOperation.Substraction))
            {
                getCalculated = mySub;
            }
            else if (operationChoice == Convert.ToInt32(typeOperation.Multiplication))
            {
                getCalculated = myMul;
            }
            else
            {
                getCalculated = myDiv;
            }

            DelegateDemoBusinessClass demobusinessclass = new DelegateDemoBusinessClass(x, y, getCalculated);

            getCalculated(x, y);

        }

        public static void myAdd(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public static void mySub(int x, int y)
        {
            Console.WriteLine(x - y);
        }
        public static void myMul(int x, int y)
        {
            Console.WriteLine(x * y);
        }
        public static void myDiv(int x, int y)
        {
            Console.WriteLine(x / y);
        }
    }


Multicast Delegate:

  • That has references to more than one function.
  • Two approaches to create multicast delegate.
  • + or += to register a method with the delegate
  • - or -= to un-register a method with the delete
  • Invokes the methods in the invocation list, the the same order in which they are added.
  • If the delegate has a return type other than void and if the delegate is a multicast delegate, only the value of the last invoked method will be returned.
  • If the delegate has an out parameter, the value of the output parameter, will be the value assigned by the last method.
  • Usage: Observer design pattern.