Friday, March 17, 2017

Extension methods in C#

   What is Extension method in C# ?

  • An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types.
  • The extension methods are called as if they were instance methods from the extended type, For example: x is an object from int class and we called it as an instance method in int class.
  • An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LINQPractice.HelperClass
{
  public static class String
  {
    public static string ConverToUpperCase(this string strg)
    {
      return strg.ToUpper();
    }
  }
}

Calling from Different class:


using System.Web.Mvc;

using LINQPractice.HelperClass;

namespace LINQPractice.Controllers
{
    public class LINQController : Controller
    {
        // GET: LINQ
        public ActionResult Index()
        {
          string str1= "vijay";
          string outputstr= str1.ConverToUpperCase();
            return View();
        }
    }
}

Important points for the use of extension methods:
  • An extension method must be defined in a top-level static class.
  • An extension method with the same name and signature as an instance method will not be called.
  • Extension methods cannot be used to override existing methods.
  • The concept of extension methods cannot be applied to fields, properties or events.
  • Overuse of extension methods is not a good style of programming.


References:

https://www.codeproject.com/Articles/34209/Extension-Methods-in-C
http://www.c-sharpcorner.com/uploadfile/puranindia/extension-methods-in-C-Sharp-3-0/




Wednesday, March 15, 2017

Difference between Deferred execution and Immediate execution in LINQ ?

Deferred Execution

In case of differed execution, a query is not executed at the point of its declaration. It is executed when the Query variable is iterated by using loop like as for, foreach.

Antother way of explain:

In LINQ, execution of a query is usually deferred until the moment when you actually request the data.

Example Code snippet:

  1. DataContext context = new DataContext();

  1. var query = from customer in context.Customers
  1. where customer.City == "Delhi"
  1. select customer; // Query does not execute her
  2.  
  1. foreach (var Customer in query) // Query executes here
  1. {
  1. Console.WriteLine(Customer.Name);
  1. }

A LINQ query expression often causes deferred execution. Deferred execution provides the facility of query reusability, since it always fetches the updated data from the data source which exists at the time of each execution.

Immediate Execution

In case of immediate execution, a query is executed at the point of its declaration. The query which returns a singleton value (a single value or a set of values) like Average, Sum, Count, List etc. caused Immediate Execution.
You can force a query to execute immediately of by calling ToList, ToArray methods.
  1. DataContext context = new DataContext();
  2. var query = (from customer in context.Customers
  3. where customer.City == "Delhi"
  4. select customer).Count(); // Query execute here
Immediate execution doesn't provide the facility of query re-usability since it always contains the same data which is fetched at the time of query declaration.


References:
http://www.dotnettricks.com/learn/linq/difference-between-deferred-execution-and-immediate-execution




Difference Between First() and FirstOrDefault() in LINQ


Here I am going To Explain Difference Between First(0 and FirstOrDefault().

At The Time Of Interview And using LINQ its necessary To Understand Differences Between First() and FirstORDefault().It IS Commonly Used Syntax While Using LINQ().

Here Is Sample Table.

Member
IDNameYearAddressIncomeUserName
1PQR2010-2011C50000S123
2PQR2012-2013C180000S123
3XYZ2013-2014B200000S789
4ABC2013-2014A350000S253
A. First()
  1. When we Use First() in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Expression in Where Clause then It Will Throw You Exception as: InvalidOperationException: Sequence contains no elements.
    1. Var x=(from m in Member  
    2. Where m.UserName=’S000’  
    3. Select m.Name,m.Income,m.Year ).First()  
    In The Member table There Is no Such Record Which Will Match the expression so Above Query will Throw: InvalidOperationException: Sequence contains no elements.
    We Can Handle This Exception In C# by using try Catch like:
    1. try  
    2. {  
    3.    Var x=(from m in Member  
    4.    Where m.UserName=’S000’  
    5.    Select m.Name,m.Income,m.Year  
    6.    ).First()  
    7.   
    8. }  
    9. catch (InvalidOperationException ex)  
    10. {  
    11.    Console.WriteLine(ex.Message);  
    12. }  
  1. When There Are Multiple Records Releted To TO Matching Expression and If You want only the First One Then You can Use First().

    i.e: 
    1. Var x=(from m in Member  
    2. Where m.UserName=’s123’  
    3. Select m.Name,m.Income,m.Year).First()  
    Then You Will get The Result Like:

    PQR2010-1150000S123
  2. First() returns First Element Of Sequence.
  3. First() throws Exception when There IS No element Presnt In Table.

B. FirstORDefault():
  1. When we Use FirstORDefault () in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Criteria in Where Clause then It Will return Some Default Value (Null).
    1. Var x=(from m in Member  
    2. Where m.UserName=’S000’  
    3. Select m.Name,m.Income,m.Year ).FirstOrDefault()  
    In The Member table There Is no Such Record Which Will Match the expression so Above Query will Return Default value as Null but Not An Exception.

    But when we use above code in c# then it might throw an Exception like:
    1. Console.WriteLine(x.Name);  
    It Will Throw An Exception ( because x has Got Null Value because Of Absence Of Record In Table): 
    “object reference not set to an instance of an object”.
    We Can Handle This Exception In C# by using try Catch like:
    1. try  
    2. {  
    3.    Var x=(from m in Member  
    4.    Where m.UserName=’S000’  
    5.    Select m.Name,m.Income,m.Year ). FirstOrDefault ()  
    6.    If(x!=null)  
    7.    {  
    8.        Console.WriteLine(x.Name);  
    9.    }  
    10.    else  
    11.    {  
    12.      Console.WriteLine("No Record Found");  
    13.    }  
    14. }  
    15. catch (Exception ex)  
    16. {  
    17.    Console.WriteLine(ex.Message);  
    18. }  
  2. When There Are Multiple Records Releted To TO Matching Expression and If You want only the First One Then You can Use First().
    i.e
    1. Var x=(from m in Member  
    2. Where m.UserName=’S123’  
    3. Select m.Name,m.Income,m.Year ).FirstOrDefault()  
    Then You Will get The Result Like:

    PQR2010-1150000S123
  3. FirstOrDefault () returns First Element Of Sequence.
  4. FirstOrDefault () does not throws Exception when There IS No element Present in Table.