Story of Equality in .Net - Part 6

Udemy

Background:

This article is in the continuation of series of articles regarding how Equality works in .Net, the purpose is to have the developers more clear understanding on how .Net handles equality for different types.

What we learned so far:

Following are the key points that we learned from the previous parts until now:
  • C# does not syntactically distinguish between value and reference equality which means it can sometimes be difficult to predict what the equality operator will do in particular situations.
  • There are often multiple different ways of legitimately comparing values. .Net addresses this by allowing types to specify their preferred natural way to compare for equality, also providing a mechanism to write equality comparers that allow you to place a default equality for each type 
  • It is not recommended to test floating point values for equality because rounding errors can make this unreliable
  • There is an inherent conflict between implementing equality, type-safety and good Object Oriented practices.
  • Net provides the types equality implementation out of the box, few methods are defined by the .Net framework on the Object class which are available for all types.
  • By default the virtual Object.Equals method does reference equality for reference types and value equality for value types, but for value types it uses reflection which is a performance overhead for value types and any type can override Object.Equals method to change the logic of how it checks for equality e.g. String, Delegate and Tuple do this for providing value equality, even though these are reference types.
  • Object class also provides a static Equals method which can be used when there is chance that one or both of the parameters can be null, other than that it behaves identical to the virtual Object.Equals method.
  • There is also a static ReferenceEquals method which provides a guaranteed way to check for reference equality.
  • IEquatable<T> interface can be implemented on a type to provide a strongly typed Equals method which also avoids boxing for value types. It is implemented for  primitive numeric types but unfortunately Microsoft has not been very proactive  implementing for other value types in the FCL( Framework Class Library ).
  • For Value Types using == operator gives us the same result as calling Object.Equals but underlying mechanism of == operator is different in IL( Intermediate Language ) as compared to Object.Equals, so the Object.Equals implementation provided for that primitive type is not called, instead an IL instruction ceq gets called which says that compare the two values that are being loaded on the stack right now and perform equality comparison using CPU registers.
  • For Reference Types== operator and Object.Equals method call both work differently behind the scenes which can be verified by inspecting the IL code generated. It also uses ceq instruction which do the comparison of memory addresses.
If you want to read the other parts published until now, you can read them here:
We will be looking at String type in this post that how Equality works for it. You might be aware that for strings the equality operator compares values not references which we had seen in the first post of this series. It is because String has overridden the implementation of Equals to behave in this manner.
We will investigate how == operator and Object.Equals method behave for equality checking.

Equality Operator and String:

Consider the following piece of code:

class Program
{
 
    static void Main(String[] args)
    {
 
        string s1 =  "Ehsan Sajjad";
        string s2 = String.Copy(s1);
 
        Console.WriteLine(ReferenceEquals(s1, s2));
        Console.WriteLine(s1 == s2);
        Console.WriteLine(s1.Equals(s2));
            
        Console.ReadKey();
 
    }
 
}

The above code is very similar to what we have looked at before as well, but this time we have String type variables in place. We are creating a string and holding its reference in s1 variable and on next line we are creating copy of the string and holding its reference in another variable names s2.

Then we are checking for reference equality for both the variables that are they both pointing to same memory location or not, then in next two lines we are checking the output of equality operator and Object.Equals method.

Now we will build the project and run it to see what it outputs on the console. The following is the output printed on console:


You can see that ReferenceEquals has returned false which means that both the string are different instances, but the == operator and Equals method have returned true, so it is clear that for Strings the equality operator does indeed test the value for equality not the reference exactly as Object.Equals does.

Behind the Scenes of Equality Operator for String

Let’s see how the equality operator is doing that. Now let’s examine the IL code generated for this example. For doing that, Open the Visual studio Developer Command Prompt, for opening it, go to Start Menu >> All Programs >> Microsoft Visual Studio >> Visual Studio Tools>> Developer Command Prompt


Type ildasm on the command prompt, this will launch the IL disassembler which is used  to look at the IL code contained in an assembly, it is installed automatically when you install Visual Studio, so you don’t need to do anything for installing it.


Click the File Menu to open the menu, and click the Open Menu Item which will bring up the window to browse the executable that we want to disassemble.


Now navigate to the location where your application executable file is located and open it.


This will bring up the code of the assembly in hierarchical form, as we have multiple classes written in the assembly, so it has listed down all the classes.

Now the code which we want to explore is in the Main Method of the Program class so navigate to the Main method and double click it to bring the IL code for it.


The IL code for main looks like this:


IL for String override of Equals Method

First let;s look at the IL generated for s1.Equals(s2), and there are no surprises as it is calling Equals method but this time it is calling the method implementation of IEquatable<string> which takes a string as argument, not the Object.Equals override is being called, because the compiler found a better match for the string argument that was supplied. See the picture below:


IL for == operator for String

Now let’s examine what is the IL generated for the string equality checking done using equality operator, so we can see the now there is no ceq instruction being called which we saw in previous posts that for value types and reference types that instruction is executed when we check for equality using == operator, but for String we have call to a new method named op_equality(string, string) which takes two string arguments, we have not seen this kind of method before, so what it is actually? 

The answer is it is the overload of C# equality operator (==) which is provided by String class. In C# when we define a type, we have the option to overload the equality operator for that type, for  example , for Person class which we have been seeing in previous examples will look like following, if we overload the == operator for it:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
 
    public static bool operator == (Person p1, Person p2)
    {
        bool areEqual = false;
        if (p1 == null || p2 == null)
            areEqual = false;
        if(p1 == null  && p2 == null )
            areEqual = true; 
        if (p1.Id == p2.Id)
            areEqual = true;
        else
            areEqual =  false;
 
        return areEqual;
    }
}


So the above code is pretty simple, We have declared an operator overload which would be a static method, but the thing to notice here is that the name of the method is operator == The similarity of declaring operator overload with static method is not a con-incidence, actually it is compiled as a static method by the compiler, because we know and had been discussed before that IL (Intermediate Language) has no concept of operators, events etc , it only understands fields and methods, so operator overload can only exist as a method which we observed in IL code above, the overload operator code is turned by compiler in to a special static method called op_Equality().

First it is checking if any of the passed instances is null then they are not equal, then we see if both are null then obviously both references are equal so it will return true, and next it checks if Id property of both references is equal then they are equal, otherwise they are not equal.

This way we can define our own implementation for our custom types according to the business requirements. As we discussed earlier that equality of two objects is totally dependent on the business flow of the application, so two objects might look equal to someone but not equal to some other according to their business logic.

This makes one thing clear that Microsoft has provided == operator overload for String class, and we can even see that if we peek in to the source code of String class in Visual Studio by using Go to Definition, which would be like:



In the above snapshot, we can see that there are two operator overload one for equality and the other is inequality operator which works exactly the same way but the negation of equality operator output.

Summary


  • We have now enough understanding of what C# Equality operator does in the case of Reference Types. Following the thing that we need to keep in mind:
    • If there is an overload for the equality operator for the type being compare, it uses that operator as a static method.
    • If there is no overload of operator for reference type, the equality operator compares the memory addresses using ceq instruction.
  • One thing to note is that Microsoft made sure that == operator overload and Object.Equals override always give the same result even though they are in fact different methods. So that is an important thing we need to keep in mind when we start implementing our own Equals override, we should also take care of the equality operator as well, otherwise our type will end up giving different result using Equals override and equality operator which would be problematic for consumers of the type. We will be seeing in another post how we can override Equals method in a proper way.
  • If we are changing how Equality works for a type, we need to make sure we provide implementation for both Equals override and == operator overload so that they both give the same result, and that’s obvious otherwise it would be confusing for other developers who will be using our implemented type .






Story of Equality in .Net - Part 5

Udemy

Background:

This article is in the continuation of series of articles regarding how Equality works in .Net, the purpose is to have the developers more clear understanding on how .Net handles equality for different types. You may want to read the previous post as well:


In the previous post (i.e. Part 4) we compared the result of equality comparison of value type using == operator and Object.Equals method and the result was same but the mechanism for evaluating the equality is different as the IL generated for Object.Equals and == operator was different, which means that == operator does not call Object.Equals behind the scenes but it uses CPU’s registers to determine if the two value type variable are equal or not.

Introduction:

I hope that after reading the previous posts, you have now better understanding how the c# equality operator works for primitive types like int, float, double etc. In this post we will be focusing on how the c# equality operator and Equals method behave for reference types either they are framework class library types or user defined custom types. If you haven’t read previous parts and interested in reading from start about this topic, you can navigate all parts published before here:


== Operator and Reference Types 

If you recall from the previous post we saw an example using reference types for equality that it checks for reference equality, now we will modify the same example to see that equality operator compiles to what in case of reference types.

class Program
{
 
    static void Main(String[] args)
    {
        Person p1 = new Person();
        p1.Name = "Ehsan Sajjad";
 
        Person p2 = new Person();
        p2.Name = "Ehsan Sajjad";
        
        Console.WriteLine(p1.Equals(p2));
        Console.WriteLine(p1 == p2);
        Console.ReadKey();
    }     
 
}


Now we will test using these both method of checking equality i.e. equality operator of c# and Equals method of Object type. If we runt his example we will see false  printed on the console two times which was expected result as Person is a reference type and those are two different instances of person with difference memory reference.

From the output we can easily deduce that both the equality operator and Equals method check for reference equality for reference types and that’s actually what’s happening.  So, Equality operator also checks reference equality not value equality for reference types just same like Equals method.

What Happens Behind the Scenes?

Now let’s examine the IL code generated for this example. For doing that, Open the Visual studio command prompt, for opening it, go to Start Menu >> All Programs >> Microsoft Visual Studio >> Visual Studio Tools>> Developer Command Prompt


Type ildasm on the command prompt, this will launch the ildasm which is used  to look at the IL code contained in an assembly, it is installed automatically when you install Visual Studio, so you don’t need to do anything for installing it.


Browse the folder where your executable is and open it using File Menu. This will bring up the IL code of your executable.

The IL code for the above C# code looks like:


If we see the IL code for p1.Equals(p2), there are no surprises, it is comparing the equality by calling the virtual Equals method of Object, and the method signatures are pretty clear, as they say it requires an object, so this is actually a virtual call to Object.Equals method, this is the best type’s method match that C# compiler picked.

Now if we look at IL code generated for equality operator comparison of the objects. It is exactly the same instruction used which we saw for the integer example in the previous part. It is not calling any method to do the comparison, it is just loading both arguments to the evaluation stack and doing a ceq, which is a dedicated IL instruction to check for equality probably using the CPU’s hardware.

You might be thinking how does that achieve the reference equality?  We know that Person is a class which is a reference type which means whatever the variable of type Person contains is the address in memory of where the Person object is on managed heap.

Both arguments p1 and p2 are holding the memory addresses and you know addresses in memory are just numbers which means that they can be compared using the ceq statement for equality just like the integers you declare in the code. In fact this ceq is comparing the addresses to see if they are equal, in other words whether the reference is pointing to the same memory address is reference equality.

Summary

  • We saw that == operator and Object.Equals method call both work differently behind the scenes which we can verify by inspecting the IL code generated.
  • We saw that for Reference types as well using == operator gives us the same result as calling Object.Equals but underlying mechanism of == operator is different in IL as compare to Object.Equals, which is that it does not uses the Object.Equals instead it uses ceq instruction which do the  comparison of memory addresses using hardware instructions .




Grid View with Server Side Filtering, Sorting and Paging in asp.net mvc 5

Udemy

 

Download Source Code


Background

In the previous post, we talked about how we can achieve a gridview type functionality in asp.net mvc same like we have in asp.net webforms. We saw that how easy it is to implement a gird using jQuery datatables plugin which provides vital features such as searching, sorting and pagination.


One thing to notice in the previous post is that all the features provided by the plugin are client side which means that all the data is loaded in the page first and then the plugin handles the data on client side for searching, pagination and sorting which is fine if the result sets coming are not very big, but it can cause problems if the table is too big or the data is not that much but grows gradually as applications is used, so if that is the case this way of creating the grid would fail in long run.

Introduction

In this post, we will be seeing how we can implement the server side pagination, searching and sorting which is of course a better approach in the long run or for the applications where datasets are too big.
We will be modifying the source code from the previous post for this, so let’s get started.

First of all, we need to install datatables.mvc5  from nuget package manager, it is a datatables model binder to controller implemented by Stefan Nuxoll. You may be thinking why we need this package, it is because the binder will provide strongly typed model posted at controller, which will help us to avoid reading the request parameter and will also save us from type-casting the parameters from Request as all the parameters posted in Request object are not type safe so we have to convert them manually to their destination type, which will help the developers to focus on business logic instead of playing around with Http parameters, checking them and casting to the right type.
 The good thing about this binder is that you can add custom parameters sent in the request if your business requirements need that.
 You can add your own custom parameters if needed by providing your own implementation of IDataTablesRequest, and you will also need to override the BindModel and MapAdditionalColumns method of it.

So now we will install datatables.mvc5 , Go to Tools >> NuGet Package Manager >> Manage Nuget Packages for Solution and click it.

The package manager will get opened and by default it will be displaying the installed nugget packages in your solution, click the Browse button and then search for datatable.mvc5 package, then select it and check the projects of the solution in which you want to install this package, in our case we are installing in it GridExampleMVC web project only as per requirement and then press the install button.



Select the correct package which is in the above screenshot the top one returned in the search results and install it.



If the installation of package goes successful, you will be able to see in the References of the project:



Go to the Index.cshtml file and update the html of the view by removing the thead and tbody elements of the table. Your updated html would be:

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-primary list-panel" id="list-panel">
            <div class="panel-heading list-panel-heading">
                <h1 class="panel-title list-panel-title">Assets</h1>
            </div>
            <div class="panel-body">
                <table id="assets-data-table" class="table table-striped table-bordered" style="width:100%;">
                </table>
            </div>
        </div>
    </div>
</div>

We removed the head and body of table because it would get generated by the datatables plugin itself. Now we will have to update the jQuery datatables initialization so that it loads data from server side via ajaxing.

For that add the following code in the Index.cshtml view:

@section Scripts
{
    
<script type="text/javascript">
        var assetListVM;
        $(function () {
            assetListVM = {
                dt: null,

                init: function () {
                    dt = $('#assets-data-table').DataTable({
                        "serverSide": true,
                        "processing": true,
                        "ajax": {
                            "url": "@Url.Action("Get","Asset")"
                        },
                        "columns": [
                            { "title": "Bar Code", "data": "BarCode", "searchable": true },
                            { "title": "Manufacturer", "data": "Manufacturer", "searchable": true },
                            { "title": "Model", "data": "ModelNumber", "searchable": true },
                            { "title": "Building", "data": "Building", "searchable": true },
                            { "title": "Room No", "data": "RoomNo" },
                            { "title": "Quantity", "data": "Quantity" }
                        ],
                        "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
                    });
                }
            }

            // initialize the datatables
            assetListVM.init();

        });

</script>
    
 }

After this, we will write the Get action code in the AssetController, for that first we need to reference the System.Linq.Dynamic namespace as we will be using the methods provided for dynamic linq in our action, for that go to Nuget Package Manager once again and search for System.Linq.Dynamic package and install it in your project.



After installing the package, go to AssetController and write the Get action implementation which will be :

public ActionResult Get([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel)
{
    IQueryable<asset> query = DbContext.Assets;
    var totalCount = query.Count();

    #region Filtering
    // Apply filters for searching
    if (requestModel.Search.Value != string.Empty)
    {
        var value = requestModel.Search.Value.Trim();
        query = query.Where(p => p.Barcode.Contains(value) ||
                                 p.Manufacturer.Contains(value) ||
                                 p.ModelNumber.Contains(value) ||
                                 p.Building.Contains(value)
                           );
     }

     var filteredCount = query.Count();

     #endregion Filtering

     #region Sorting
     // Sorting
     var sortedColumns = requestModel.Columns.GetSortedColumns();
     var orderByString = String.Empty;

     foreach (var column in sortedColumns)
     {
        orderByString += orderByString != String.Empty ? "," : "";
        orderByString += (column.Data) + (column.SortDirection == Column.OrderDirection.Ascendant ? " asc" : " desc");
     }

     query = query.OrderBy(orderByString == string.Empty ? "BarCode asc" : orderByString);

     #endregion Sorting

     // Paging
     query = query.Skip(requestModel.Start).Take(requestModel.Length);


     var data = query.Select(asset => new
     {
        AssetID = asset.AssetID,
        BarCode = asset.Barcode,
        Manufacturer = asset.Manufacturer,
        ModelNumber = asset.ModelNumber,
        Building = asset.Building,
        RoomNo = asset.RoomNo,
        Quantity = asset.Quantity
     }).ToList();

     return Json(new DataTablesResponse(requestModel.Draw, data, filteredCount, totalCount), JsonRequestBehavior.AllowGet);
}


Now build the project, and run it in browse to see the working grid view with server side filtering, paging and sorting in action.



Beginners Guide for Creating GridView in asp.net mvc 5

Udemy

Download Source Code


Introduction

In this post, we will be seeing how we can create a grid view in asp.net mvc, same like we have in asp.net web form. There are many their party both server side and also client side plugins written in jQuery are available which provide all the essential functionalities that we have in web forms which include searching, sorting and paging etc. It totally depends on the requirements of specific application if the search is needed client side or server side, same for the other functions.

You can download the source code from this link.

Libraries Available

Some of the libraries and plugins available are:
·         Grid.Mvc
·         MVCGrid.NET
·         PagedList.MVC
·         JQuery.Grid
·         JQuery Grid for ASP.NET MVC
·         JQuery DataTables

Using Jquery DataTables

All have their pros and cons, but personally I have found jQuery datatables to be a good choice. It is highly flexible. It supports pagination, instant-search, multi-column ordering. It also supports almost all the data sources to which it can be binded, some of which are:
·         DOM
·         JavaScript
·         Ajax
·         Server-side processing

One of the best option which I like in it is that it supports both client side searching, pagination, sorting etc, but it also provides option to have server side processing of it, as there can be case where we have too much data in database and in that case client side paging wouldn’t be a good option, just think millions of rows in a table and if they are binded to it using client side pagination, it will make or page unresponsive due to high amount of rows processing and html rendering.

We will first see an example of how we can implement it using client side processing. So, let’s get started. We will have a working grid with searching, sorting and paging at the end of the post which will look like:


First of all create database and table that we will be using in this post, Open SQL Management Studio and run the following script:

CREATE DATABASE [GridExampleMVC]  
 GO  
   
 CREATE TABLE [dbo].[Assets] (  
     [AssetID]                   UNIQUEIDENTIFIER NOT NULL,  
     [Barcode]                   NVARCHAR (MAX)   NULL,  
     [SerialNumber]              NVARCHAR (MAX)   NULL,  
     [FacilitySite]              NVARCHAR (MAX)   NULL,  
     [PMGuide]                   NVARCHAR (MAX)   NULL,  
     [AstID]                     NVARCHAR (MAX)   NOT NULL,  
     [ChildAsset]                NVARCHAR (MAX)   NULL,  
     [GeneralAssetDescription]   NVARCHAR (MAX)   NULL,  
     [SecondaryAssetDescription] NVARCHAR (MAX)   NULL,  
     [Quantity]                  INT              NOT NULL,  
     [Manufacturer]              NVARCHAR (MAX)   NULL,  
     [ModelNumber]               NVARCHAR (MAX)   NULL,  
     [Building]                  NVARCHAR (MAX)   NULL,  
     [Floor]                     NVARCHAR (MAX)   NULL,  
     [Corridor]                  NVARCHAR (MAX)   NULL,  
     [RoomNo]                    NVARCHAR (MAX)   NULL,  
     [MERNo]                     NVARCHAR (MAX)   NULL,  
     [EquipSystem]               NVARCHAR (MAX)   NULL,  
     [Comments]                  NVARCHAR (MAX)   NULL,  
     [Issued]                    BIT              NOT NULL,  
     CONSTRAINT [PK_dbo.Assets] PRIMARY KEY CLUSTERED ([AssetID] ASC)  
 )  
 GO

There is complete sql script file attached in the source code, so you can use it to create the database and table with sample data.

Now, create a new asp.net mvc 5 web application. Open Visual Studio 2015. Go to File >> New >> Project



From the dialog navigate to Web and select ASP.Net Web Application project and click OK.


From Templates, Select MVC, check the unit tests if you will write unit tests as well for your implementations and click OK.
Our project is created with basic things in place for us. Now we will start by creating the database context class as we will be using Entity Framework for the Data Access.

First of all we need to create model for the Asset table which we will be using for retrieving data using ORM.
In Model folder, create a new class named Asset:

using System.ComponentModel.DataAnnotations;

namespace GridExampleMVC.Models
{
    public class Asset
    {
        public System.Guid AssetID { get; set; }

        [Display(Name = "Barcode")]
        public string Barcode { get; set; }

        [Display(Name = "Serial-Number")]
        public string SerialNumber { get; set; }

        [Display(Name = "Facility-Site")]
        public string FacilitySite { get; set; }

        [Display(Name = "PM-Guide-ID")]
        public string PMGuide { get; set; }

        [Required]
        [Display(Name = "Asset-ID")]
        public string AstID { get; set; }

        [Display(Name = "Child-Asset")]
        public string ChildAsset { get; set; }

        [Display(Name = "General-Asset-Description")]
        public string GeneralAssetDescription { get; set; }

        [Display(Name = "Secondary-Asset-Description")]
        public string SecondaryAssetDescription { get; set; }
        public int Quantity { get; set; }

        [Display(Name = "Manufacturer")]
        public string Manufacturer { get; set; }

        [Display(Name = "Model-Number")]
        public string ModelNumber { get; set; }

        [Display(Name = "Main-Location (Building)")]
        public string Building { get; set; }

        [Display(Name = "Sub-Location 1 (Floor)")]
        public string Floor { get; set; }

        [Display(Name = "Sub-Location 2 (Corridor)")]
        public string Corridor { get; set; }

        [Display(Name = "Sub-Location 3 (Room No)")]
        public string RoomNo { get; set; }

        [Display(Name = "Sub-Location 4 (MER#)")]
        public string MERNo { get; set; }

        [Display(Name = "Sub-Location 5 (Equip/System)")]
        public string EquipSystem { get; set; }

        public string Comments { get; set; }

        public bool Issued { get; set; }

    }
}


Now Navigate to Models folder from Solution Explorer and open IdenityModels.cs file , we will add a property for the Asset table in the database context, which will be the Entity Framework representation of Asset table which we created using the script. Add new property in the ApplicationDbContext class:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public DbSet Assets { get; set; }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}


The above is the default entity framework settings for asp.net identity 2.0, we are extending it with our own tables for which we have added new DbSet for Asset table.

Now add an empty controller in Controllers folder named AssetController, which we will be using for all the Asset related work. Here is how it should look like:


public class AssetController : Controller
    {
        // GET: Asset
        public ActionResult Index()
        {
            return View();
        }
    }


Now we will install jQuery datatables that we will be using to build the gird, Go to Tools >> NuGet Package Manager >> Manage Nuget Packages for Solution and click it.


The package manager will get opened and by default it will be displaying the installed nugget packages in your solution, click the browser button and then search for jQuery datatables package, then select it and check the projects of the solution in which you want to install this package, in our case we are installing in it GridExampleMVC web project only as per requirement and then press the Install button.






Visual Studio will prompt to tell that it is going to modify the solution, you will have to press ok to continue the installation of the package.

After the nugget package is installed successfully, we need to include the necessary js and css of jquery datatables in the view where we will use it, for that we have to register the jquery datatables, for that open the BundleConfig.cs file locate in App_Start folder and add the following code for css and js files at the end:

bundles.Add(new ScriptBundle("~/bundles/datatables").Include(
                        "~/Scripts/DataTables/jquery.dataTables.min.js",
                        "~/Scripts/DataTables/dataTables.bootstrap.js"));

bundles.Add(new StyleBundle("~/Content/datatables").Include(
          "~/Content/DataTables/css/dataTables.bootstrap.css"));


After registering the scripts and css for datatables, we need to add them in our master layout which is by default _Layout.cshtml located in Views >> Shared which is defined in the _ViewStart.cshtml located in the same location.






Before writing the controller code, we need to configure the connection string for entity framework that will be used to connect database when it will be doing database operations i.e. running queries. So our connection string should be pointing to a valid data source so that our application won’t break when we run it.


For that open web.config and provide the connection string for the database. In config file you will find the under configuaration node connectionStrings, you will need to modify the connection string in that node according to your system. In my case it looks like:

<connectionstrings>
    <add connectionstring="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=GridExampleMVC;Integrated Security=True;MultipleActiveResultSets=true" name="DefaultConnection" providername="System.Data.SqlClient"/>
</connectionstrings>

Now in controller add a property for database context that we will be using for querying the database.

private ApplicationDbContext _dbContext;

public ApplicationDbContext DbContext
{
    get
    {
        return _dbContext ?? HttpContext.GetOwinContext().Get();
    }
    private set
    {
        _dbContext = value;
    }

}

This property we will be using to query the database with entity framework in all actions of the controller wherever needed.

Now in the index action, we will simply fetch all the rows of the table and pass it to view:

public ActionResult Index()
{
    return View(DbContext.Assets.ToList());
}


Our complete controller class code now looks like:

using GridExampleMVC.Models;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity.Owin;


namespace GridExampleMVC.Controllers
{
    public class AssetController : Controller
    {

        private ApplicationDbContext _dbContext;

        public ApplicationDbContext DbContext
        {
            get
            {
                return _dbContext ?? HttpContext.GetOwinContext().Get();
            }
            private set
            {
                _dbContext = value;
            }

        }

        public AssetController()
        {

        }

        public AssetController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        // GET: Asset
        public ActionResult Index()
        {
            return View(DbContext.Assets.ToList());
        }
    }
}

Here comes the view part now, where we will write code about how it should render as html. So create a view with Template Empty (Without Model) for the Index action and add the following code in it:

@model IEnumerable< GridExampleMVC.Models.Asset>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-primary list-panel" id="list-panel">
            <div class="panel-heading list-panel-heading">
                <h1 class="panel-title list-panel-title">Assets</h1>
            </div>
            <div class="panel-body">
                <table id="assets-data-table" class="table table-striped table-bordered" style="width:100%">
                    <thead>
                        <tr>
                            <th>Bar Code</th>
                            <th>Manufacturer</th>
                            <th>Model Number</th>
                            <th>Building</th>
                            <th>Room No</th>
                            <th>Quantity</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var asset in Model)
                        {
                            <tr>
                                <td>@asset.Barcode</td>
                                <td>@asset.Manufacturer</td>
                                <td>@asset.ModelNumber</td>
                                <td>@asset.Building</td>
                                <td>@asset.RoomNo</td>
                                <td>@asset.Quantity</td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@section Scripts
{
    
 <script type="text/javascript">
     $(document).ready(function () {

         $('#assets-data-table').DataTable();
     });
    </script>   
    
 }

Now run the application and you will see a grid with sorting, searching and filtering available in it, but there is one problem in it, which is it is processed on client side, all the data is rendered by view when action is called which may make page performance slow or increases page load time if there are a large number of rows coming.

We will be seeing in another post how we can make it more better by using server side paging, sorting and filtering which is surely a better approach where we have huge data set.



Story of Equality in .Net - Part 4

Udemy

Background:

This article is in the continuation of the previous three articles regarding how Equality works in .Net, the purpose is to have the developers more clear understanding on how .Net handles equality for types. You may want to read the previous post as well:


Introduction

I hope that after reading the previous three posts, you have now understanding how the .Net framework deals with the Equality using the virtual Object.Equals method and for most of the value types and for few of Reference types using IEquatable<T>. In this post we will be discussing the c# equality operator provided by Microsoft. We will explore what the C# Equality operator does and how it works. After reading this post I hope you will have a better understanding what it means when you check for equality of two variable using == operator.

We will cover the following things:
  • We will be writing some code for comparing the == operator and Object.Equals behavior for same parameters to see what happens, and we will see that the result is same, but the mechanism used for both is different
  • We will see how C# equality operator works for primitive types.
C# also provides inequality operator as well, the syntax for which is !=. We will not be discussing this operator in detail because it is the negation of what equality operator does, so they are not that much different. For example, if a==b evaluates to true then a!=b should evaluate to false and vice versa. Apart from this difference both the operators work exactly the same way. So, keep in mind that everything that we will discuss in this post about equality operator also applies to the inequality operator as well, it will just inverse the return value.

The equality operator is used when we want to evaluate that if two of the variables are equal or not. A lot of developers have misconception that this operator is basically the same as Object.Equals method, and it is just a syntactical convenience provide by C# language.

This is not true actually. It is being designed in a way that it often gives the same result which by calling Object.Equals will give but that’s not always the case as the underlying mechanism is completely different.

== Operator and Primitive Types

We will see with example code that how the equality operator uses different mechanism in reference to Object.Equals method.

    class Program
    {
 
        static void Main(String[] args)
        {
            int num1 = 5;
            int num2 = 5;
 
            Console.WriteLine(num1.Equals(num2));
            Console.WriteLine(num1 == num2);
 
 
            Console.ReadKey();
        }     
 
 
    }



We are comparing two integers for equality using both way , first using Object.Equals overload for integer and second one using c# equality operator and we will examine the generated IL code which will help us understand how they are different in mechanism.
Of course when we will run this program it will evaluate to true for both the statements, and you can test it on your machine as well. As the result of both the statements is same this makes us believe that both are using Object.Equals and checking two integers for equality.



What Happens Behind the Scene

As we talked earlier that the == operator and Object.Equals work differently and we are going to see that how it is which will be a proof to what we talked earlier. We will examine the IL generated for both the statements after compilation.

One thing to note here is that before doing this you will need to build your project using Release build not debug, as debug code will generate a lot of unnecessary instructions that are helpful when we need to debug and also in debug build it will use Object.Equals implementation for both, so that will not help you to see what we will discuss next.

For doing that, Open the Visual studio command prompt, for opening it, go to Start Menu >> All Programs >> Microsoft Visual Studio >> Visual Studio Tools>> Developer Command Prompt




Type ildasm on the command prompt, this will launch the ildasm which is used  to look at the IL code contained in an assembly, it is installed automatically when you install Visual Studio, so you don’t need to do anything for installing it.



Browse the folder where your executable is and open it using File Menu. This will bring up the IL code of your executable.



Expand the Program class and double click the Main method, it will open up the intermediate language for Main method:




You don’t need to understand all the code written in it, if you have not seen IL seen before that may look complex to you, but you don’t need to understand all the instructions.
We will just look at the lines where the comparison is done for both ways to show you the difference, you can see the following line:

IL_0007:  call       instance bool [mscorlib]System.Int32::Equals(int32)

Here it is calling the Object.Equals implementation provided via IEquatable<int> for integer type, in IL we need to specify the method call using Fully Qualified name, so the above statements say to call Equals method which takes as int32 as parameter and method exists in System.Int32 type and this type exists in mscorlib assembly.

Now look at IL generated for second comparison which was done via equality operator, which is:

IL_0013:  ceq

You can see that call to Equals method in Int class is not called in this case, instead we have an IL instruction written ceq which says that compare the two values that are being loaded on the stack right now and perform equality comparison using CPU registers. So, C# equality operator uses ceq statement to do equality check for primitive types and it does not calls the Object.Equals implementation provided by that primitive type.




Summary

  • We compared the == operator with Object.Equals method in this post.
  • We saw that using == operator gives us the same result as calling Object.Equals but underlying mechanism of == operator is different in IL as compare to Object.Equals, which is that it does not uses the Object.Equals instead it uses probably cpu registers to do the comparison.
 



Story of Equality in .Net - Part 3

Udemy

Introduction

After reading,

 Story of Equality in .Net - Part 1  
 Story of Equality in .Net - Part 2

you can see that Object.Equals method has two problems. One thing is that it lacks strong typing and for value types boxing needs to be done. In this post we will look at the IEquatable<T> interface which provides solution to these problems.

IEquatable<T> Interface

The generic IEquatable <T> exists for solving a slightly different problem with Equals method. The Equals method on Object type takes parameter of type Object. We know that this is the only type of parameter which is possible if we want Object.Equals to work for all types.
But Object is a reference type which means that if you want to pace a value type as an argument, the value type would be boxed which will be a performance hit which is bad. Typically when we define value type instead of reference type is because we are concerned of performance, so we always want to avoid this performance overhead of boxing and unboxing.
There is also another problem, having an object as parameter means that there is no type safety. For Example, the following code will compile without any problem:

    class Program
    {
 
        static void Main(String[] args)
        {
            Person p1 = new Person("Ehsan Sajjad");
 
            Program p = new Program();
 
            Console.WriteLine(p1.Equals(p));
 
 
            Console.ReadKey();
        }        
 
    }



There is nothing to stop me for calling Equals method on two difference type of instances. We are comparing instance of Person class with instance of Program and compiler didn’t stopped me doing that, which is clearly an issue as both are totally different types and there is no way they can meaningfully equal each other.


This was just an example, you should not be doing this kind of comparisons in your code, and obviously it would be nice if compiler could pick up this kind of situation, right now it cannot because Object.Equals method does not have strong type safety.
We can solve this boxing and type safety issue by having an Equals method that takes the type being compare as parameter, so for example we can have an Equals method on String which takes a string as parameter and   we can have an Equals method on Person class which takes a Person variable as parameter. This will solve both boxing and type safety problem nicely.

As we talked in the previous post about the problem of inheritance with the above approach. But there is no way to usefully define these strongly typed methods on System.Object, because System.Object does not know what types will be deriving from it.
So how can we make a strongly typed Equals method generally available to consume. Microsoft solved this problem by providing the interface IEquatable<T> which can be exposed by any type that wants to provide strongly typed Equals method. If we look at the documentation we can see that IEquatable<T> exposes just one method called Equals which returns a bool.


This serves  exactly the same purpose  as Object.Equals, but it takes the generic type T instance as a parameter and therefore it is strongly typed which means for value types there will be no boxing to be  done.

IEquatable<T> and Value Types

We can illustrate the IEquatable<T> interface with one of the simplest type integer.

        static void Main(String[] args)
        {
            int num1 = 5;
            int num2 = 6;
            int num3 = 5;
 
            Console.WriteLine(num1.Equals(num2));
            Console.WriteLine(num1.Equals(num3));

        }


We have three integer variables which we are comparing using Equals and printing the result on the console. If we look at the intellisense, we can see that there are two Equals method for int, one of them takes object as parameter and that’s the overridden Object.Equals method, other one takes an integer as parameter, this Equals method is implementation of IEquatable<int> by integer type, and this is the overload which will be used for comparison of the above example code, because in both Equals call we are passing integer as parameter not object, so the compiler will pick the overload defined for IEquatable<int> as it is the best signature match.


 This is obviously very unnatural way to compare integers, normally we just write like:

    Console.WriteLine(num1 == num2);

We have written the code via Equals method so that you can see that there are two Equals method out there. All primitive supports provide the implementation for IEquatable<T> interface. Just take the above example, int implements the IEquatable<int>.


Likewise other primitive types also implement IEquatable<T>. Generally IEquatable<T> is very useful for value types. Unfortunately Microsoft had not been very consistent about implementing it for non-primitive value types in the Framework Class Library, so you can’t always rely on this interface to be available

IEquatable<T> and Reference Types

.IEquatable<T> is not that much useful for reference types as it is for value types. Because for reference types there is not really any performance issues like we had for value types (boxing) which needs fixing and also for the reason that IEquatable<T> does not play nicely with inheritance.

But it is worth noting here that String which is a reference type does implements IEquatable<T>.  If you recall from the Part – 2, when we were demonstrating the Equals method for string we were explicitly casting the string variable to object.

        static void Main(String[] args)
        {
            string s1 = "Ehsan Sajjad";
            string s2 = string.Copy(s1);
            
            Console.WriteLine(s1.Equals((object)s2));

        }


That was to make sure that it call the Object.Equals override which takes object as parameter, if we don’t do that then compiler will pick the strongly typed Equals method and that method is actually the implementation of IEquatable<string> implemented by String . String is a sealed class so you cannot inherit from it, so the issue of conflict between Equality and Inheritance does not arise.

Obviously you would expect that when both Equals method are available on a type, the virtual Object.Equals method and the IEquatable<T> Equals method, they should always give the same result. That’s’ true for all the Microsoft implementations and it’s one of the things that is expected of you when you implement this interface yourself.
If you want to implement IEquatable<T> interface, then you should make sure that you override the Object.Equals method to do exactly the same thing as your interface method does and that makes sense, because it should be clear that if a type implements two versions of Equals that behave differently, then developers who will consume your type will get very confused.

Summary

·         We saw that we can implement IEquatable<T> on our types to provide a strongly typed Equals method which also avoids boxing for value types.
IEquatable<T> is implemented for  primitive numeric types but unfortunately Microsoft has not been very proactive  implementing for other value types in the Framework Class Library



Story of Equality in .Net - Part 2

Udemy

Introduction

In this post, we will see how smartly .Net handles equality and comparison out of the box. This means that you will be able to understand how .Net handles some of the issues that we discussed in the previous post.

If you remember from previous post,there are 4 methods in Object class which are provide by .Net framework for the purpose of equality checking but each one is designed for different scenarios but their purpose is same which is to check equality of two objects. In this post we will be focusing on the following three methods out of the four which are:
  1. virtual Object.Equals
  2. static Object.Equals
  3. static Object.ReferenceEquals

We will start by looking in detail at the virtual Object.Equals method. This provides the most important mechanism for equality checking in .Net, since it is the means by which any type can tell what equality means for itself. We will see how out of the box this method gives you reference equality for most reference types but value equality for all value types.
We will also compare it with the static method Object.Equals() which is of same name which is more robust when the scenario is that instances to be checked for equality can be null.

We will also see how we can guarantee that the equality check is done on the reference of instances not the values of the instances using the static Object.ReferenceEquals method.

After reading this post, I hope that you will have a good understanding what equality means in .Net.

Virtual Object.Equals() Method

As we discussed in the previous post as well, in .Net there are number of ways to compare equality, but the most fundamental way .Net provides for this purpose is the virtual Object.Equals() method defined in the System.Object type.

To see this method in action, we will create a class which represents a kind of person. The only thing our class contains is a string field containing the name of the person and a constructor that enforces to set the value of the name field.

    public class Person
    {
 
        private string _name;
 
        public string Name 
        { 
            get 
            { 
                return _name; 
            } 
        }
 
        public Person(string name)
        {
            _name = name;
        }
 
        public override string ToString()
        {
            return _name;
        }
 
    }

Now we will write the Main method to use this type.

    static void Main(String[] args)
    {
        Person p1 = new Person("Ehsan Sajjad");
        Person p2 = new Person("Ahsan Sajjad");
            
        Console.WriteLine(p1.Equals(p2));
    }  


As you can see in Main we are creating two instances of Person class passing different value as parameter to the constructor, and then on the next line we are checking for equality using the Object.Equals method. The equal method returns a Boolean, it returns true if both items are equals and false if they are not equal, we are writing the result of the equality comparison on the console to see what it outputs.
You would hope from the code that the two instances are not equal as “Ehsan Sajjad”  and “Ahsan Sajjad” are not equal they have different sequence of characters, and of course if we run the code we will see false as output on the console. So Equals() appears to be working right here and if you notice we didn’t have to do anything in our Person class definition to achieve this. The Equals method is provided by System.Object  so it is automatically available on all types, because all types ultimately derive from System.Object
By the way I suspect some of you may be looking at this code and thinking that the line p1.Equals(p2) is not what we write normally for checking equality, if we want to check for equality, we just write this p1 == p2, but the point here is we need to understand how equality works in .Net and the starting point for that is the Equals method.

== Operator and Equals Method

If you write == in your code, you are using the C# equality operator and that is a very nice syntactical convenience C# language provides to make the code more readable but it is not really part of the .Net Framework. .Net has no concept of operators, it works with methods. If you want to understand how equality works in .Net then we need to start with the things that .Net Framework understands. So we will only be using .Net methods in this post for most of the code, so you can see how it works , that means some of the code  you will see may look un-natural  but we will discuss  the == (c# equality operator) in another post.

Now let’s get back to the fun part i.e. code, we will declare another instance of Person in the Main program

This new instance p3 also passes same value in the constructor as p1 which is “Ehsan Sajjad”, so what do you think what will happen if we try to compare p1 with p3 using the Equals method, let’s try and see what happens:

    static void Main(String[] args)
    {
        Person p1 = new Person("Ehsan Sajjad");
        Person p2 = new Person("Ahsan Sajjad");
        Person p3 = new Person("Ehsan Sajjad");
            
        Console.WriteLine(p1.Equals(p3));
    } 


This also returns false, these two instances p1 and p3 are not equal and the reason is the base Object.Equals method evaluates reference equality, its implementation tests  whether two variables refers to the same instance, in this case it is obvious to us and that p1 and p3 have exactly the same value, both instances contains the same data but Equals method does not care about that, it care only about that they are same or different instances, so it returns false telling us that they are not equal.

As we discussed earlier in this post and in previous post as well that Equals is a virtual method in Object type which means that we can override it, if we want the Equals method to compare the values of the Person instances, we can override the Equals method  and can define our own implementation for how to compare two Person instances for equality, there is nothing unusual in this, Equals is a normal virtual method, we are not going to override it yet though, if you want to stick to good coding practices you need to do few other things when you override Object.Equals method, we will see later how to do that, for this post we will just stick to what Microsoft has given us  out of the box.

Equals Method Implementation for String

There are couple of reference types for which Microsoft has overridden the Object.Equals method in order to compare values instead of references, probably the well know of these and certainly the one that’s most important to be aware of is String, we will examine with a small program the demonstration of that:

    static void Main(String[] args)
    {
        string s1 = "Ehsan Sajjad";
        string s2 = string.Copy(s1);
            
        Console.WriteLine(s1.Equals((object)s2));
    }


In this program we initialize a string and store it’s reference in s1, then we create another variable s2 which contains the same value but we initializer s2 by creating a copy of the value s1 has, string.Copy method’s name is pretty descriptive, it creates and returns the copy of the string and then we are using Equals method to compare them.
You can see that we are casting argument of Equals method explicitly to object type that obviously you would not want to do in the production code, the reason we have done that here is to make sure that implementation of override of Object.Equals() is called, as string define multiple Equals method and one of them is strongly type to string i.e. it  takes string as parameter, if we didn’t cast it to object then the compiler would have considered the strongly typed method a better parameter when resolving overloads and would have called that one, that is obviously  better when we are normally programming and both method will actually do the same thing  but we explicitly wanted to show how the object.Equals override behaves, so we needed to cast parameter to object to tell the compiler to avoid strongly typed overload and use the object type override.

If we run the above code will see that it returns true. The override provided by Microsoft for string type compares the contents of the two string instances to check whether they contains exactly the same characters in the same sequence and returns true if they are otherwise returns false, even if they are not the same instance.

There are not many Microsoft defined reference types for which Microsoft has overridden Equals method to compare values, apart from String type, two others types that you must be aware of are Delegate and Tuple, calling Equals on these two will also compare the values, these are the exceptional ones all other reference types Equals will always do Reference equality check.

Equals Method and Value Types

Now we will see how Equals method works for value types, we will be using the same example that we used at start of the post (Person class ) but we will change it to struct instead of class for seeing the behavior in case of value type

    public struct Person
    {
 
        private string _name;
 
        public string Name 
        { 
            get 
            { 
                return _name; 
            } 
        }
 
        public Person(string name)
        {
            _name = name;
        }
 
        public override string ToString()
        {
            return _name;
        }
 
    }

What you think what will happen now if we run the same program again, as we know struct is stored on  the stack, they don’t have references normally unless we box them, that’s why they are called value type not reference type
    static void Main(String[] args)
    {
        Person p1 = new Person("Ehsan Sajjad");
        Person p2 = new Person("Ahsan Sajjad");
        Person p3 = new Person("Ehsan Sajjad");
            
        Console.WriteLine(p1.Equals(p2));
        Console.WriteLine(p1.Equals(p3));
    }

So as we know that the implementation of Object.Equals do the reference comparison in case of reference types but in this case you might think that comparing references does not makes sense as struct is a value type.

So let’s run the program and see what it prints on the console.


You can see that this time the result is different, for the second case it is saying that both instances are equal, it is exactly the result you would expect if you were to compare the values of both p1 and p3 instances of Person  to see if they were equal and that is actually happening in this case, but if we look at the Person type definition we have not added any code for overriding the Equals method of Object class, which means there is nothing written in this type to tell the framework that how to compare the values of instances of Person type to see if they are equal.


.Net already knows all that, it knows how to do that, .Net framework has figured out without any effort from us that how to tell p1 and p3 have equal values or not, how is that happening. What actually happening is that as you may already know that all struct types inherits from System.ValueType which ultimately derives from System.Object.
System.ValueType itself overrides the System.Object Equals method, and what the override does is that it traverses all the fields in the value type and call Equals against each one until it either finds any field value that is different or all fields are traversed, if all the fields turn out to be equal, then it figures out that these two value type instances are equal. In other words, value types override the Equals method implementation and says that both instances are equal if every field in them has same value which is quite sensible. In the above example our Person type has only one field in it which is the backing field for the Name property which is of type string and we already know that calling Equals on string compares values and the above results of our program proves what we are stating here. That’s how .Net provides the behavior of Equals method for value types very nicely.

Performance Overhead for Value Types

Unfortunately, this convenience provide by .Net framework comes with a price. The way System.ValueType Equals implementation works is by using Reflection. Of course it has to if we think about it. As System.ValueType is a base type and it does not know about how you will derive from it, so the only way to find out what fields in out defined type (in this case Person) has is to do it using Reflection which means that performance would be bad

Recommended Approach for Value Types

The recommend way is to override the Equals method for you own value types which we will see later how to provide that in a way that it runs faster, in fact you will see that Microsoft has done that for many of the built-in value types that comes with the framework which we use every day in our code.

Static Equals Method

There is one problem when checking for equality using the virtual Equals method. What will happen if one or both of the references you want to compare is null. Let’s see what happens when we call Equals method with null as argument. Let’s modify the existing example for that:

    static void Main(String[] args)
    {
        Person p1 = new Person("Ehsan Sajjad");
                        
        Console.WriteLine(p1.Equals(null));
    }

If we compile this and run, it returns false and it should and makes perfect sense because it is obvious that null is not equal to non-null instance and this is the principle of Equality in .Net that Null should never evaluate as equal to Non-Null value.

Now let’s make it vice versa to see what will happen if the p1 variable is null, then we have a problem. Consider that we don’t have this hardcoded instance creation code instead of that this variable is passed as parameter from some client code which uses this assembly and we don’t know if either of the value is null.
If p1 is passed as null, executing the Equals method call will throw a Null Reference Exception, because you cannot call instance methods against null instances.
The Static Equals method was designed to address this problem, so we can use this method if we are not aware if one of the objects could be null or not, we can use it this way:

    Console.WriteLine(object.Equals(p1,null));

Now we are good to go without worrying about if either of the instance reference is null, you can test it by running with both scenarios and you will see it works fine, and of course it would return false if one of the reference variable is null.

Some of you may be wondering that what would happened if both the arguments passed to Static Equals method are null, if you add the following line to test that:

    Console.WriteLine(object.Equals(null,null));

You will see that it returns true in this case, in .Net null is always equal to null, so testing whether null is equal to null  should always evaluate to true.

If we dig in to the implementation Static Equals method we will find that it is very simple implementation. Following is the logic of it if you look in to the source code of Object type:

public static bool Equals(object x, object y)
{
    if (x == y) // Reference equality only; overloaded operators are ignored
    {
        return true;
    }
    if (x == null || y == null) // Again, reference checks
    {
        return false;
    }
    return x.Equals(y); // Safe as we know x != null.
}


If first checks if both parameters refer to the same instance i.e. what == operator will do, this check will evaluate to true causing method to return true if both the parameters are null, the next if block will return false if one of the parameters is null and other one is not, finally if control reaches the else block then we know that both parameter point to some instance, so we will just call the virtual Equals method.
This means that the static Equals method will always give the same result as the virtual method  except that it checks for null first, as static method call the virtual method, if we override the virtual Equals method, our override will automatically be  picked by the static method, that’s important as we want both static virtual methods to behave consistently.

ReferenceEquals Method

ReferenceEquals serves a slightly different purpose from the two Equals method which we have discussed above. It exists for those situations where we specifically want to determine whether the two variables refer to the same instance. You may have question in mind that Equals method also checks reference equality then why a separate method.
Those two methods do check reference equality, but they are not guaranteed to do so, because the virtual Equals method can be overridden to compare values of the instance not the reference.
So, ReferenceEquals will give the same result as Equals for types that don’t have overridden the Equals method. For example, take the Person class example which we used above. But it’s possible to have different results for types that have overridden the Equals method. For Example, the String class.

Let’s modify the string class example that we used earlier in this post to demonstrate this:

    static void Main(String[] args)
    {
        string s1 = "Ehsan Sajjad";
        string s2 = string.Copy(s1);
            
        Console.WriteLine(s1.Equals((object)s2));
        Console.WriteLine(ReferenceEquals(s1,s2));
    }

If we run this example, we will see that the first Equals call returns true just as before, but the ReferenceEquals method call returns false, and why is that?

It is telling that both string variables are different instances even though they contain the same data and if you recall what we discussed in previous post that String type overrides Equals method to compare the value of two instance not the reference.

You know that in C# static methods cannot be overridden which means you can never change the behavior of ReferenceEquals method which makes sense because it always needs to do the reference comparison.

Summary

  • We learned how .Net provides the types equality implementation out of the box
  • We saw that few methods are defined by the .Net framework on the Object class which are available for all types .
  • By default the virtual Object.Equals method does reference equality for reference types and value equality for value types by using reflection which is a performance overhead for value types.
  • Any type can override Object.Equals method to change the logic of how it checks for equality e.g. String, Delegate and Tuple do this for providing value equality, even though these are reference types.
  • Object are provides a static Equals method which can be used when there is chance that one or both of the parameters can be null, other than that it behaves identical to the virtual Object.Equals method.
  • There is also a static ReferenceEquals method which provides a guaranteed way to check for reference equality.