Tuesday 15 December 2015

New Cool Features available in C# 6

In this post we are going to see new features available in the C# 6.0 version, New version of C# have new features it's because of Roslyn compiler .

C# 6.0 features can be used in visual studio editor, by doing the following settings, 

  1. Go to the properties of  a project 
  2. select the Build tab
  3. click the Advanced button
  4. select the C# to 6.0 
  5. Then click OK. Now the Visual studio using the C# 6.0 version to build the project.


Features available are : 
1. Auto-property initializes
2. Null value checking in object execution
3 Conditional Catch block
4. Expression bodied function
5. Expression bodied function members
6. Await in Catch/Finally block
7. Static members invocation
8. nameof function
9. Dictionary Initializers 
10. String interpolation

Auto property initialize:
Here after we can initialize the value of property in the declaration itself, when declaring a property we can set the value of the property like below


        public string LastName { setget; } = "G";

Null value checking in object execution:
Now we can check the object null, before execute the in build method or properties of a object in a single, This can be done by write the ?. operator after the object. if the object is null then the further property or method will not executed and return have a false expression type

            Person employee = null; 
            employee?.GetFullName();

Conditional Catch Block:
From the new version we can place the condition on the Catch block, to tell the compiler which part of the Catch block need to be executed when the exception raised, based on the condition.


            try
            {
                employee = null;               
                throw new Exception("Sample error");
            }
            catch(Exception ex) when(employee==null)
            {
                WriteLine($"Employee is null {ex.Message}");
            }
            catch(Exception ex)
            {
                WriteLine($"Error Message is : {ex.Message}");
            }


Expression bodied function:
Expression can be used in defining a function, Functions can be mention in a single line by the use of  Expression  statement


 /* Expression body function */
    public string GetFullName() => $"{FirstName} {LastName}";


Expression bodied function members:
Expression can be used in defining a members of a class in a single line


 /* Expression body function members */
    public string Address => "Chennai";

Await in Catch/Finally block:
Now here after we can use the Await in Catch and Finally block in the code, this code is very useful for the async operations


            catch(Exception ex)
            {
              await Logger.Write () ;
                WriteLine($"Error Message is : {ex.Message}");
            }



Static members invocation:
In the newer version we can use the static methods straight away in the code , instead of using the Class as prefix, Here we are using the Class declaration in the namespace by using the Static keyword


using static System.Console;
using static Samples.ExtensionMethods;

            /* Name of a Object */
            WriteLine("Hi");


nameof Function
nameof function is used for the developers to find the name of the object or property at the runtime, instead of declare the variable for the display name


 /* Name of a Object */
   WriteLine(nameof(employee));


Dictionary initialize 
The new way of Dictionary Initialize will make a clear understanding dictionary among the developers


          /* New Way of Dictionary intializers */
            Dictionary<intPerson> emplist = new Dictionary<intPerson>()
            {
                [0] = new Person() { FirstName= "Suresh",LastName = "G",Age = 25},
                [1] = new Person() { FirstName = "Ramu", LastName = "D" ,Age = 3},
                [2] = new Person() { }
            };


String interpolation
now we can format the string in a easy way by declare the variable directly in string by make a $interpolation declaration before string and declare the variable inside the curly braces
            
        public static void PrintWithStyle(string messgae)
        {
            WriteLine("********************************");
            WriteLine($"{messgae}");
            WriteLine("********************************\n");
        }

            
            catch(Exception ex) 
            {
                WriteLine($"Employee is null {ex.Message}");
            }





From this post you can learn some pf the new features available in the C# 6.0





Sunday 13 December 2015

Usage of IComparer , IComparable and IEqualityComparer interfaces

In this post we are going to see the real usage of following interfaces IComparer, IComparable and IEqualityComparer.

IComparer is a interface which is used to sort the Array, this interface will force the class to implement the 
Compare(T x,T y) method, which will compare the two objects. The instance of the class which implemented this interface is used in the sorting of the Array.

IComparable is a interface is implemented in the type which needs to compare the two objects of the same type, This comparable interface will force the class to implement the following method  CompareTo(T obj)

IEqualityComparer is a interface which is used to find the object whether it is Equal or not, Now we will see this in a sample where we have to find the Distinct of a Object in a collection. This interface will implement a method 
Equals(T obj1,T obj2)

Now we take a Example we have a Employee class , based on this class we have to create a Collection. Now we have the following requirements.

1. Sort the Array using Array class
2. Need an collection using Linq : Remove the Duplicate, Order by higher to lower, Remove one employee id

    abstract public class Person
    {
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Address { setget; }
    }

    public enum SortType
    {
        ByID,
        BySalary
    }


IComparer
 public class EmployeeIdSorter : IComparer<Employee>
        {
            public int Compare(Employee x, Employee y)
            {
                if (x.Id < y.Id)
                    return 1;
                else if (x.Id > y.Id)
                    return -1;
                else
                    return 0;
            }
        }

        public class EmployeeSalarySorter : IComparer<Employee>
        {
            public int Compare(Employee x, Employee y)
            {
                if (x.Salary < y.Salary)
                    return 1;
                else if (x.Salary > y.Salary)
                    return -1;
                else
                    return 0;
            }
        }



IComparable
      public int CompareTo(Employee other)
        {
            if (this.Id < other.Id)
                return 1;
            else if (this.Id > other.Id)
                return -1;
            else
                return 0;
        }


IEqualityComparer
        public class EmployeeDistinctEquality : IEqualityComparer<Employee>
        {
            public EmployeeDistinctEquality()
            {

            }

            public bool Equals(Employee x, Employee y)
            {
                if (x == null && x == null)
                    return true;
                else if (x == null || y == null)
                    return false;
                else if (x.Id == y.Id)
                    return true;
                else
                    return false;
            }

            public int GetHashCode(Employee obj)
            {
                return obj.Id.GetHashCode();
            }
        }


Sorting:
Array.Sort(inputarray, Employee.SorterType(SortType.ByID));
            return inputarray;

Linq :
  IEnumerable<Employee> result = employees.Distinct(Employee.EmpDistinct())
                .OrderByDescending(x => x.Id).Where(x => x.Id != idToRemove);



Full Code :

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

namespace SAmples
{
    abstract public class Person
    {
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Address { setget; }
    }

    public enum SortType
    {
        ByID,
        BySalary
    }

   
    public class Employee:PersonIComparable<Employee>
    {
        public int Id { getset; }
        public int Salary { setget; }

        public int CompareTo(Employee other)
        {
            if (this.Id < other.Id)
                return 1;
            else if (this.Id > other.Id)
                return -1;
            else
                return 0;
        }

        public static IComparer<Employee> SorterType(SortType type)
        {
            switch (type)
            {
                case SortType.ByID:
                    return new EmployeeIdSorter();
                    
                case SortType.BySalary:
                    return new EmployeeSalarySorter();
                   
                default:
                    return new EmployeeIdSorter();                   
            }
        }

        public static IEqualityComparer<Employee> EmpDistinct()
        {
            return new EmployeeDistinctEquality();
        }

        public class EmployeeIdSorter : IComparer<Employee>
        {
            public int Compare(Employee x, Employee y)
            {
                if (x.Id < y.Id)
                    return 1;
                else if (x.Id > y.Id)
                    return -1;
                else
                    return 0;
            }
        }

        public class EmployeeSalarySorter : IComparer<Employee>
        {
            public int Compare(Employee x, Employee y)
            {
                if (x.Salary < y.Salary)
                    return 1;
                else if (x.Salary > y.Salary)
                    return -1;
                else
                    return 0;
            }
        }

        public class EmployeeDistinctEquality : IEqualityComparer<Employee>
        {
            public EmployeeDistinctEquality()
            {

            }

            public bool Equals(Employee x, Employee y)
            {
                if (x == null && x == null)
                    return true;
                else if (x == null || y == null)
                    return false;
                else if (x.Id == y.Id)
                    return true;
                else
                    return false;
            }

            public int GetHashCode(Employee obj)
            {
                return obj.Id.GetHashCode();
            }
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine();

            Employee[] employees = new Employee[] {
                 new Employee() { Id=3, FirstName = "Ramu", LastName="R", Address="Pune" },
                new Employee() { Id =1,FirstName="Rajesh",LastName="G", Address="Chennai" },
                new Employee() { Id=2,FirstName="Suresh", LastName="G",Address="Chennai" },
               new Employee() { Id=3, FirstName = "Ramu", LastName="R", Address="Pune" },       
              new Employee() { Id=5, FirstName = "Sundar", LastName="S", Address="Madurai" },
                new Employee() { Id=3, FirstName = "Ramu", LastName="R", Address="Pune" },
                new Employee() { Id=4,FirstName="Shiny", LastName="N", Address="US"},
                new Employee() { Id=3, FirstName = "Ramu", LastName="R", Address="Pune" },
            };
         
            int idToRemove = 5;

            IEnumerable<Employee> result = employees.Distinct(Employee.EmpDistinct())
                .OrderByDescending(x => x.Id).Where(x => x.Id != idToRemove);

            Print(result.ToArray());

            Console.WriteLine("\n********************");
            
            Sorting(employees);
            Print(employees);

            Console.Read();


        }

        static void Print(Employee[] result)
        {        
            foreach (Employee emp in result)
                Console.WriteLine(" ID :"+emp.Id+"  Name : "+emp.FirstName);
            
        }

        static Employee[] Sorting(Employee[] inputarray)
        {
            Array.Sort(inputarray, Employee.SorterType(SortType.ByID));
            return inputarray;
        }

    }

   
  

}


Output:




From the output you can see the First print have a distinct collection with sort order using the IComparer, distinct is achieved by using the IEqualitycomparer

From this post you can learn what is the real usage of IComparer, IComparable and IEqualityComparer interfaces.