C# basics: why we override Equals method

You may have come across questions,

  • Why to override Equals method?
  • How to determine whether two object are equal?
  • How to determine whether two objects are identical?

To get answer of all the above questions, let us consider Product class as listed next:

 


class Product
    {
        public int Price { get; set; }
        public string Name { get; set; }
            
    }

We are creating two instances of the Product class, foo and loo. The foo is assigned to loo. Both objects are pointing to the same reference, hence we will get true as expected output for all the Equals.

 


Product foo = new Product {Price = 10,Name= "foo"};
            Product loo = new Product();
             loo = foo; 
             var valueEqual = foo.Equals(loo);
            Console.WriteLine(valueEqual); 

            var objRefEqual= Object.ReferenceEquals(foo, loo);
            Console.WriteLine(objRefEqual);

            var objEqual = Object.Equals(foo,loo);         
            Console.WriteLine(objEqual);
            Console.ReadKey(true);

Expected output is,

clip_image002

Now let us go ahead and modify the instances as listed next:

 


Product foo = new Product {Price = 10,Name= "foo"};
            Product loo = new Product();
            loo.Price = 10;
            loo.Name = "foo";
            var valueEqual = foo.Equals(loo);
            Console.WriteLine(valueEqual); 

            var objRefEqual= Object.ReferenceEquals(foo, loo);
            Console.WriteLine(objRefEqual);

            var objEqual = Object.Equals(foo,loo);         
            Console.WriteLine(objEqual);
            Console.ReadKey(true);


This time you will get output as false for all the three Equals method.

clip_image002[6]

However if you closely observe, value of the both properties of both objects are exactly the same. Price and the Name property is set to 100 and foo respectively. But still we are getting Equals returns false for the foo and the loo object.

We can observe that, even though properties values are same Equals returns false. Essentially, when arguments are referring to different objects. Equals don’t check for the values and always returns false. We can say that by default Equals check for IDENTITICAL OBJECTS rather than EQUAL OBJECTS

Understanding Internal

To understand this behavior, let us examine the System.Object class. It contains,

  1. One virtual Equals method.
  2. One static Equals method. This takes two arguments. Returns true if they are identical otherwise false.
  3. One static ReferenceEquals method. This takes two arguments. Returns true if both arguments are same instance otherwise false.

Clearly CLR Equals method does not check for the values, when arguments refers to different objects. So by default it checks for the Object Identity rather than Object Equality.

Why to override Equals()

We may come across the requirement to check for object equality. To check whether both objects contains same properties value or not. This can be done by override the Equals method. We can override Equals method as listed next:

 

class Product
    {
        public int Price { get; set; }
        public string Name { get; set; }
        public override bool Equals(object obj)
        {
           if (obj == null)
                return false;
            if (this.GetType() != obj.GetType()) return false;

            Product p = (Product)obj;
            return (this.Price == p.Price) && (this.Name == p.Name);
        }        
    }


While overriding the Equals method, you should consider the followings

  • If object argument is null, return false
  • If type of object argument is different than type of this, return false
  • If object argument is neither null nor its type is different check for the values of the instance fields. If they are equal return true else return false

We have overridden Equals method, now if you compare the objects which is listed next, you will find that Equals returns true if Objects are equal whereas ReferenceEquals returns false when objects are different.

 

Product foo = new Product {Price = 10,Name= "foo"};
            Product loo = new Product();
            loo.Price = 10;
            loo.Name = "foo";
            var valueEqual = foo.Equals(loo);
            Console.WriteLine(valueEqual); 

            var objRefEqual= Object.ReferenceEquals(foo, loo);
            Console.WriteLine(objRefEqual);

            var objEqual = Object.Equals(foo,loo);         
            Console.WriteLine(objEqual);
            Console.ReadKey(true);


You will get the expected output true, false and true.

clip_image002[8]

Summary

We started with the question that why to override Equals method? We learnt that by default System.Object Equals method does not check for the equality of the objects. It checks only for the objects identity. To check objects equality, we override the Equals method.

C-Sharp Basics: What is Checked and Unchecked operations

You may have come across questions,

  • What is checked and unchecked primitive operations?
  • How to handle overflow in C-Sharp?
  • Does CLR handles overflow or developers?

So let us start with understanding a program. Consider the code listed below:

 


    static void Main(string[] args)
        {
           
                Byte b = 100;
                b = (Byte) (b + 200);
                Console.WriteLine(b);
         
            Console.ReadKey(true);
        }


On running you will get 44 as the output. There is one serious observation about the above output is that Bye is primitive type which is unsigned 8 bit value. Even though above add operation results an overflow, CLR is not complaining about that.

By default, CLR does not throw overflow exception.

However there may be a requirement in which, you may have to throw the overflow exception. CLR gives us the option to configure whether overflow exception should be thrown or not.

We can configure this at three level

  1. Statements level.
  2. Operations level
  3. Application level

Application level

You can configure to throw overflow exception at the project level. To configure, right click on the project, select properties and then build, and then advanced. In the advanced build setting check the checkbox- check for arithmetic overflow/underflow

clip_image002

After configuring check for arithmetic overflow/underflow at the project level, if you go ahead and run the application, CLR will throw an exception as shown next,

clip_image004

We are getting the overflow exception since we have configured at the project level that throw exception on arithmetic overflow/underflow.

Statements level

You may not want to throw the exception for all the operations in the project. So you can also configure whether to throw overflow/underflow exception or not at the statement or expression level.

C# provides us checked and unchecked operator and statement to configure overflow/underflow exception at the operation and statement level respectively.

Using the check statement, you can throw overflow exception in above code as listed below:

 


static void Main(string[] args)
        {
            checked
            {

                Byte b = 100;
                b = (Byte)(b + 200);
                Console.WriteLine(b);
            }
               
         
            Console.ReadKey(true);
        }


By using the check statement, we can as CLR to throw overflow or underflow exception caused by the arithmetic operations.

Operations level

C# also allows us to apply cheeked/unchecked operator on a single expression. Above code can be written as listed next:

 

static void Main(string[] args)
        {
                Byte b = 100;
                b = checked ((Byte)(b + 200));
                Console.WriteLine(b);
                Console.ReadKey(true);
        }


Understanding Internal

CLR has two instructions for each arithmetic operations.

Addition: add and add.ovf

Subtraction: sub and sub.ovf

Multiplication: mul and mul.ovf

Conversion: conv and conv.ovf

As instruction name suggests add instruction does not throw overflow exception whereas add.ovf throws overflow exception. When we perform add operation by default CLR executes add IL instruction. However when we perform checked add operation, CLR executes add.ovf exception which will throw overflow exception.

Summary

There were three questions in the beginning, let us see them one by one

What is checked and unchecked primitive operations?

Checked and unchecked operations check for the overflow in the arithmetic operations. If checked then operation may throw the overflow/underflow exception. If unchecked then it will not throw the overflow exception.

How to handle overflow in C-Sharp?

Using the checked and unchecked overflow can be handled in the C#.

Does CLR handles overflow or developers?

By default CLR does not throw overflow exception. However using checked and unchecked developer can configure whether to throw or not.

How to create a Container in Azure Storage from MVC application

I am working on a MVC application in which I need to work with Microsoft Azure storage .I had a requirement to create An Azure storage container from the MVC application. In this post I will share my learning that how I created a container programmatically.

I created the view as shown in below image. User has to enter the azure storage account name, azure storage key and the name of the container to be created.

image

Above View is MVC razor view, and it is created using the cshtml as shown below:

 


@{
    ViewBag.Title = "BLOB Manager";
}
<div class="jumbotron">
    <div class="row">
        <div class="col-md-8">
            <section id="loginForm">
                @using (Html.BeginForm("AzureInfo", "Manage", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                {
                    @Html.AntiForgeryToken()
                    <h2> Manage BLOB Container</h2>
                    <hr />
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountName", "", new { @class = "form-control", @placeholder = "Account Name" })
                            @Html.ValidationMessage("AccountName", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountKey", "", new { @class = "form-control", @placeholder = "Account Key" })
                            @Html.ValidationMessage("AccountKey", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("ContainerName", "", new { @class = "form-control", @placeholder = "Container Name" })
                            @Html.ValidationMessage("containername", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group input-group input-group-lg">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Create Container" class="btn btn-lg btn-success" />
                        </div>
                    </div>

                }
            </section>
        </div>
    </div>
</div>

Above I am creating,

  • Three text boxes with the placeholder and the class set to bootstrap form-control
  • A submit button with the class set to bootstrap btn-lg and btn-success
  • All the controls are inside the form.
  • On form post operation, AzureInfo action of the Manage controller will be called.

Once the View is ready, let us go ahead and create an azure utility class. In this class we will put all the operations related to the azure storage. But before that you need to add Azure storage library to the project. Either you can use NuGet package manager or console to add the library. I am using console to install Azure storage library. I have taken the 4.3 version because at the time of writing this post, this was the latest stable version available.

image

Once package is successfully installed, add following namespaces.

 


using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure;

To create the container in the Azure storage, I have created a function CreateContainer. This function takes three input parameters, account name, account key and the container name.

 


public static class AzureUtility
    {
        public static string  CreateContainer(string AccountName, string AccountKey, string ContainerName)
        {

            string UserConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(UserConnectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(ContainerName.ToLower());
            if (container.CreateIfNotExists())
            {
                container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
                return container.Name;
            }
            else
            {
                return string.Empty;
            }
        }
    }

Now let us examine the above code line by line.

  • In first line I created the connection string for the azure storage. It takes two parameters, account name and the account key. These values are passed as input parameter to the function. I am using these two parameter to create connection string.
  • Using CloudStorageAccount to parse the connection string from the constructed string.
  • Creating the CloudBlobClient
  • Getting the container reference of the BLOB.
  • If container reference does not exist, creating new container.
  • On successful creation of the container function returns name of the container else empty string.

 


[HttpPost]
        public ActionResult AzureInfo(string AccountName, string AccountKey, string ContainerName)
        {

           var result= AzureUtility.CreateContainer(AccountName, AccountKey, ContainerName);

           if (result != string.Empty)
             {

                 return RedirectToAction("Index", "Home");
             }
             else
             {
                 return RedirectToAction("Index");
             }
        }

In the action we are using the utility class to create the container. In this way an azure container can be created from the MVC application.

I hope it is useful. Thanks for reading. Happy Coding.

Related entities in Entity Framework Code First approach

In this post we will learn to create relationship between entities in the Entity Framework Code First approach.

Setting up

We are going to create three tables and set up the relationship between them.

  1. BankUser
  2. BankUserAccount
  3. Nomniee

To create tables we will create entities further in the post. For table creation the context class has been created as follows.

 

public class Context : DbContext
    {

        public Context ()
	        {
                     Database.SetInitializer<Context>(new DropCreateDatabaseIfModelChanges<Context>());
	        }

        public DbSet<BankUser> BankUser {get;set;}
        public DbSet<BankUserAccount> BankUserAccount  {get;set;}

        public DbSet<Nominee> Nomniee { get; set; }
    }


Keep in mind that, very likely you will get build error if you try to build the project as of now.

One to many relationship

Let us say we have two entities. One for the bank user and another for the bank user’s accounts. A bank user can have any numbers of the bank accounts. Typically a bank user will have following properties

    public class BankUser
    {
   
        public string   ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set;  }
        public string Sex { get; set; }

    }


A bank user can have any number of bank accounts. To map this we will have to create one NAVIGATION PROPERTY in the BankUser class. A navigation property holds entities which are related to this particular entity. An entity can have any number of related entities. Since BankUserAccount(we will create this entity later) is a related entity of the BanUser entity. So it will be as the navigation property of the BankUser account. One bank user can have any numbers of bank user account, so we will have to create collection BankUserAccount entity as the navigation property of the BankUser entity. To do this, modify the above class as below:

public class BankUser
    {
   
        public string   ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set;  }
        public string Sex { get; set; }

        public virtual ICollection<BankUserAccount> Accounts { get; set; }

    }

We define navigation property as virtual such that while reading the data we can take advantage of the entity framework lazy loading feature.

public class BankUserAccount
    {
        public string ID { get; set; }
        public double Amount { get; set; }
        public string? EmergencyContact { get; set; }
        public DateTime LastTransaction { get; set; }
        public virtual BankUser BankUser { get; set; }
    }

By this time relationship between the two tables has been created as shown below:

image

And BankUserAccount table is created as follows:

image

One to one relationship

In one to one relationship between two entities, one act as the primary entity and another as the dependent entity. Primary key of the primary entity will be used as foreign key of the dependent entity. An entry cannot be created in the dependent entity without having a reference in the primary entity. Okay enough of theory let us go ahead and see an example. So far we have seen that a bank user can have multiple bank accounts. However a particular bank account can have only one nominee. So primary key of BankUserAccount entity will act as foreign key of the Nominee entity. You can create a Nominee entity with the foreign key as shown below:

 

  public class Nominee
    {


       public string ID { get; set; }

       public string Name { get; set; }

       public string Age { get; set; }      
       [Required]
       public virtual BankUserAccount BankUserAccount { get; set; }
    }


As you see navigation property BankUserAccount is attributed with the REQUIRED. So we cannot create a Nominee entity without providing the bank user account.

By this time relationship between the two tables has been created as shown below:

image

And the Nominee table is created as below:

image

As you can see that in the Nominee table BankUserAccountID is the foreign key. Primary key of the Nominee table is different than the foreign key. So one person can be nominee of any number of bank accounts.

Other options could be, and in my opinion absolute one to one relationship. In this scenario one person can only be nominee to one bank user account. In this case you will have to modify the BankUserAccount as follows:

 

public class BankUserAccount
    {
        public string ID { get; set; }
        public double Amount { get; set; }
        public string EmergencyContact { get; set; }
        public DateTime LastTransaction { get; set; }
        public virtual BankUser BankUser { get; set; }
        public virtual Nominee Noinee { get; set; }
    }


By this time relationship between the two tables has been created as shown below:

image

And the Nominee table is modified as below:

image

Now to create the database in the local db you don’t need to modify the connection string and make a use of context class as below,

 

Context context = new Context();
            BankUser c1 = new BankUser
            {
                ID=  "C5",
                Age = 32,
                Name= "DJ",
                Sex= "Male",
               

            };
            context.BankUser.Add(c1);
            context.SaveChanges();

            var result = context.BankUser.ToList();
            foreach (var r in result)
            {
                Console.WriteLine(r.Name);
            }
            Console.ReadKey(true);

In this way you can create relationship between entities in the entity framework. I hope this post is useful.

Happy coding.

How to Clone a Git repository in Visual Studio

In my trainings, often I get a question from junior developers that how to clone a Git repository in the visual studio? Perhaps it may be very simple for senior developers, however for the developers who struggle to get it right steps are discussed below,

Step 1

Find the URL of the remote git repository. For GitHub repository URL can be found as shown in the image below. Copy the URL from here.

image 

Step 2

Launch Visual Studio and from the View select Team Explorer. In the Team Explorer window select Clone.

clip_image002

On clicking Clone, you will get an option to provide the URL of the Git repo and the choose folder in which repository will be cloned. In the URL section paste the remote repository URL as whon in the below image:

clip_image004

As the last step click on the Clone and the remote Git repository will be cloned in the Visual Studio in the given folder. If everything goes right you will get success message as shown below.

clip_image006

I hope it helps. Thanks and Happy Coding.