Pranay Rana: 2016

Tuesday, April 12, 2016

Diffence between list of user defined types

Below is discussion about finding out difference between two lists of elements.

Easiest way to find out difference between two list is make use of method Except, which is introduced with Linq feature in .Net framework 3.5.

Except method works as below



So when except method is applied on two List A and List B, it get list of all element which are present in list A only.

Let’s understand same by writing Code

List<int> a = new List<int>() { 2, 4, 7, 9, 4 };
List<int> b = new List<int>() { 8, 6, 7, 3, 4 };

var lst = a.Except(b);
foreach (var ele in lst)
{
    Console.WriteLine(ele);
}
Above code defines two list of integer, and apply Except method to find difference between them.

Output 
 


Output prints 2 & 9, which are the element in “List a” and not in “List b”. If one want to find out element which are present in “List b” and not in “List a”, than code will be like

var lst = b.Except(a);//pint output 8,6 & 3

Note:
Except method returns element of the collection which is on left side, it doesn’t get list of those element of the right side collection element which is not part of left side collection.

Except on User Defined typed List
Below is explain about how Except works when applied on user-defined data type, to understand this let’s defined employee class

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

After defining Employee class below code creates two list of Employee and applies Except method on it

List<Employee> lstA = new List<Employee>() { new Employee { ID = 1, Name = "Abc" }, 
                         new Employee { ID = 2, Name = "Pranay" },
                         new Employee { ID = 3, Name = "Hemang" }};
 List<Employee> lstB = new List<Employee>() { new Employee { ID = 4, Name = "Xyz" }, 
                         new Employee { ID = 2, Name = "Pranay" },
                         new Employee { ID = 5, Name = "Virendra" }};

var lst = lstB.Except(lstA);
foreach (var ele in lst)
{
     Console.WriteLine(ele.ID + " " + ele.Name);
}

Output 
 


So output print out all the element of list B, rather than printing elements which are not present in list A.
Problem here is when Except method applied on user-defined datatype it tries to compare references of object to find difference between lists.

Resolution
To resolve problem, there is need to use Except overload method which takes list as first input and Custom Equality Comparer as its second parameter for type. Custom Equality comparer helps to do comparison between object of list and returns difference between list.

public class EmployeeComparer : IEqualityComparer<Employee>
{
     bool IEqualityComparer<Employee>.Equals(Employee x, Employee y)
     {
        if (x == null || y == null)
            return false;

        return x.ID == y.ID;
     }

    int IEqualityComparer<Employee>.GetHashCode(Employee obj)
    {
       if (obj == null)
           return 0;

       return obj.ID.GetHashCode();
    }
}
Above code defines Custom Employee comparer which implements IEqualityComparer and does comparison of employee objects based on ID property defined in employee class.

Now when Except method applied on list as in below code,

List<Employee> lstA = new List<Employee>() { new Employee { ID = 1, Name = "Abc" }, 
                         new Employee { ID = 2, Name = "Pranay" },
                         new Employee { ID = 3, Name = "Hemang" }};

List<Employee> lstB = new List<Employee>() { new Employee { ID = 4, Name = "Xyz" }, 
                         new Employee { ID = 2, Name = "Pranay" },
                         new Employee { ID = 5, Name = "Virendra" }};

var lst = lstB.Except(lstA, new EmployeeComparer());
foreach (var ele in lst)
{
     Console.WriteLine(ele.ID + " " + ele.Name);
}
Output 
 


Output prints element of list B which are not present in List A of employee. So comparer makes it easy to find difference between two lists.

Sunday, March 20, 2016

Event Vs Deleagte

Post is explains basics of Events & Delegate and most importantly explains what is difference between both.
Both Event & Delegate is based on overserved pattern of GOF, which is based on giving notification of change in one thing (object) to all others who is interested in change. Below image is graphical interpretation of same.



Delegates
Delegate in C# is reference type, which hold reference to the function and invokes function when called with Invoke method. If one is coming from C++/C background, delegate is like pointer to function which points to function.
To understand delegate better way have look to below sample code.

    public class DelegateTest
    {
        public delegate void Print(string val);

        public DelegateTest()
        {
            Print p = new Print(PrintValue);
            p += new Print(PrintData);
            p.Invoke("Test");
        }

        private void PrintData(string s)
        {
            Console.WriteLine("PrintData" + s);
        }

        public void PrintValue(string s)
        {
            Console.WriteLine("PrintValue" + s);
        }
    }

When above class get invoked following output will get printed
PrintData Test
PrintValue Test

Key points in above code
  1. It defines delegate which can points to method with void return type and take string as input
  2. In constructor of type, it create reference object of delegate which points to method “PrintData” and “PrintValue”.
  3. Invoke method of delegate calls both methods one by one
Read more about Delegate : https://msdn.microsoft.com/en-in/library/900fyy8e(v=vs.71).aspx

Events
Event in C# is of type Delegate, which means that if one wants to use event than one must need to define delegate first. Event can have multiple event-handler functions which are of signature like delegate which get called when event raised by some event in application Simple Example is Button click on UI. Event is very useful to create notification.
To understand delegate better way have look to below sample code.

    public class EventTest
    {
        public delegate void Print(string val);
        public event Print PrintEvent;

        public EventTest()
        {
            this.PrintEvent +=  PrintData;
            this.PrintEvent += PrintValue;
        }

        public virtual void OnPrintEvent()
        {
            if (PrintEvent != null)
                PrintEvent("Test");
        }

        private void PrintData(string s)
        {
            Console.WriteLine("PrintData" + s);
        }

        public void PrintValue(string s)
        {
            Console.WriteLine("PrintValue" + s);
        }
    }

When above class object is created and then “OnPrintEvent” method invoked following output will get printed
PrintData Test
PrintValue Test

Key points in above code
  1. Its creates delegate which can point to method with return type void and take string as argument
  2. It defines Event which is of type defined delegate
  3. In Constructor, event holds two delegate i.e. Event handlers. It can also be written like
  4.           this.PrintEvent += new Print (PrintData);
              this.PrintEvent += new Print (PrintValue);
    
  5. OnPrintEvent method checks event is holding event handler function or not, if there is any event handler(s) it calls all event handlers.
Read more about Event : https://msdn.microsoft.com/en-in/library/8627sbea%28v=vs.71%29.aspx

Event VS Delegate
Both event and delegate does the same task, which is hold event handlers and call them when delegate/event invoked. So one always has question, what is need of Event in language C# when one can achieve same thing with Delegate.

Answer is Event is wrapper on Delegate type.

Problem With Delegate
Let’s understand this, using same class defined above which is “DelegateTest”.
    class Program
    {

        static void Main(string[] args)
        {
            Program p = new Program();
            DelegateTest delegateTest = new DelegateTest();
            delegateTest.p = new DelegateTest.Print(p.TestString);
            delegateTest.p = null;
        }

        public void TestString(string s)
        {
        }
    }
Above doe does following things
  1. It creates object of type DelegateTest
  2. Its assigns new delegate reference to delegate Print and override value assigned in constructor
  3. Its assigns “null” to Print delegate and removes all added function.

Problem with Delegate is that one can easily override delegate property and that lead to error or serious issue. That means one cannot use delegate as public property.

Solution with Event
To avoid above problem C# has Events, Which defines wrapper around delegate. (Below code make use of EventTest class defined above and as form above code PrintEvent is wrapper around Print delegate).
static void Main(string[] args)
        {
            Program p = new Program();
            EventTest eventTest = new EventTest();
            //eventTest.PrintEvent = null;//Not allowed in C#
            eventTest.PrintEvent += p.TestString;
        }

        public void TestString(string s)
        {
        }
Above does following things
  1. It defines object of type EventTest
  2. its assigns eventhandler to PrintEvent event of EventTest
One cannot do below things with Event
	eventTest.PrintEvent = null;//Not allowed in C#
	eventTest.PrintEvent = new PrintEvent()//Not allowed in C#

So Event type resolve problem of exposing delegate outside class by defining wrapper around delegate. Below image is presentation of Event & Delegate.



Another Difference between Event & Delegate is
  1. Event is very helpful to create Notification system. Same is not possible with delegate because delegate cannot be exposed as public.
  2. Delegate is very helpful to create call back function i.e can pass delegate as function argument, which is not possible with Event.
Conclusion
Event and Delegate are both follows Observer pattern. Difference between both is Event wraps Delegate type and which makes delegate not modifiable in terms of changing reference i.e. assign new object is not possible.

Tuesday, February 9, 2016

Reference type modification vs change of reference

Post is regarding misconception related to modifying reference type variable and assigning new reference object to reference type variable.

Let’s understand misconception by using code, below is customer class created to understand it.

Public class Customer 
{
 Public int ID{get; set;}
 Public string Name {get; set;}
}

Modification of Reference type
 
Customer cust = new Customer { ID = 1, Name = "abc" }; //defines new class 
Console.WriteLine("cust name : " + cust.Name);
cust.Name = "xyz"; //modifies value of name field and modifies cust variable
Console.WriteLine("modified cust name : " + cust.Name);

Above code creates new object of customer class and modifies it.

Customer cust1 = cust; //cust1 now has reference to cust
cust1.Name = "abc xyz"; // modification to Name field of cust1 modifies both cust1 and cust
Console.WriteLine("after cust1 modification name " );
Console.WriteLine("cust name : " + cust.Name);
Console.WriteLine("cust1 name : " + cust1.Name);

Output


Above code assigns reference of already created object cust to cust1. Because cust1 holding reference to same object as cust1 modification to cust1 also change cust. This means both cust and cust1 points only to one object.




Change of Reference i.e. Assigning new reference type object

But what happens when assigns null to cust variable

cust = null;
Console.WriteLine("after cust=null");
if (cust==null)
   Console.WriteLine("cust is null ");
Console.WriteLine("cust1 name : " + cust1.Name);

Ouput


Now most of developer thinks as cust is null than cust1 is also null. But this is not true because when you give new reference to cust , both cust and cust1 point to different location.



Assigning null cust variable is can also be as below

Customer cust = new Customer { ID =2 , Name =”customer abc”}

So when you assign new value to any reference its point to new memory location i.e. new object. Which also means that assigning new value to reference variable is doesn’t affect old reference variable.

What happens in case of method?

Now Consider scenario where developer pass reference variable to method

Modification of Reference type

Customer cust = new Customer { ID = 1, Name = "abc" }; //defines new class 
Console.WriteLine("cust name : " + cust.Name);
Program p = new Program();
p.ChangeCustomer(cust);
Console.WriteLine("modified cust name after call to changecustomer : " + cust.Name);

public void ChangeCustomer(Customer cust)
{
     cust.Name = "xyz"; //modifies value of name field and modifies cust variable
     Console.WriteLine("modified cust name in changecustomer : " + cust.Name);
}

Above code defines new customer object and pass customer object to method which does modification to object.

Method modifies customer name, so does it modifies customer object also. Output below prints modified customer name in method and same name after call returns to caller.

So this is similar to case discussed above.

Output 



Change of Reference i.e. Assigning new reference type object

Now consider below scenario

Customer cust = new Customer { ID = 1, Name = "abc" }; //defines new class 
Console.WriteLine("cust name : " + cust.Name);
Program p = new Program();
p.ChangeCustomer1(cust);
Console.WriteLine("modified cust name after call to changecustomer1 : " + cust.Name);

public void ChangeCustomer1(Customer cust)
{
    cust = new Customer { ID = 1, Name = "abc xyz" };
    Console.WriteLine("modified cust name in changecustomer1 : " + cust.Name);
}  

Above code defines new customer object and pass customer object to method which does modification to object.

Method in this code assigns new customer object to pass cust variable. So it print output as below



Output prints different name. Reason behind this is method doesn’t modify varible but it’s changing reference value it points by assigning new customer object.

So this is similar to case discussed above.

Solution to above is either return newly created object as below

public Customer ChangeCustomer1(Customer cust)
{
    cust = new Customer { ID = 1, Name = "abc xyz" };
    Console.WriteLine("modified cust name in changecustomer1 : " + cust.Name);
    return cust;
}

Or make use of ref with variable name

public void ChangeCustomer1(ref Customer cust)
{
    cust = new Customer { ID = 1, Name = "abc xyz" };
    Console.WriteLine("modified cust name in changecustomer1 : " + cust.Name);
}

Conclusion 

Above discussion it’s clear that modification to reference variable happens when you do change in original reference variable and assigning new object to variable does modify the reference i.e. memory location object points to.