What is the Extension Method in C#?

Read full article on Infragistics blog

I often get questions about the Extension Method in C#. The Extension Method was introduced in C# Version 3.0. and allows us to add functionalities in an existing class without modifying it, extending it, or re-compiling it.

Essentially, the Extension Method allows us to add a new method to an existing class:

  • · Without modifying it or adding code
  • · Without extending it or creating a new derived type
  • · Without recompiling the class

image

Extension methods are a special kind of static method but can be called on objects like an instance method. So, an extension method can be used in the same way as normal instance methods.

Steps to create an Extension Method

Step 1: Define a static visible class which will contain the Extension Method or Extension Methods. Make sure the class is visible to the client code by applying the appropriate accede modifier.

Step 2: Create a static method with at least the same visibility level as the containing class.

Step 3: The first parameter of the Extension Method always specifies the type method operates on. Make sure the type name is preceded with the “this” modifier.

Step 4: In the calling code, add the namespace that contains Extension Method class.

Step 5: Use the Extension Method on the type in the same instance method can be used. Keep in mind that we do not need to pass the first parameter because that denotes the type, however we should pass the second parameter onwards to call the extension method.

Read full article on Infragistics blog

The Top 5 New Features in C#6.0

Visual Studio 2015 recently introduced a new version of C# named C#6.0. I would not say it has major features added like Extension Method or LINQ in C# 3.0 or Async/ Await in C# 5.0. However it has many features that simplify the syntaxes and improve the readability of the code. Major C# 6.0 features include:

  • Initializers for auto-properties
  • Getter-only auto-properties
  • Expression-bodied function members
  • Using the static statement
  • Null-conditional operators
  • String interpolation
  • nameof expressions
  • Index initializers
  • Exception filters
  • Await in catch and finally blocks
  • Extension Add methods in collection initializers etc.

In this post, I will discuss the top 5 five features of C# 6.0, offcousre according to me

Auto-property initializers

In C# 6.0, a new feature has been added to set the default values of the public properties, called Auto-property initializers. Using the auto-property initializers, we can set default values to the properties without having to use a constructor. Let us consider a simple example of the Author class as shown in the listing below:

image

As you notice in the above listing, the default value of the Articles property is set to 10. So while creating the object, if the value of the Articles property is not set then it would be set to the default value 10. In the below listing, we are not setting the value of the Articles property of the object a, hence it is set to the default value of 10.

image

The auto-property initializer sets the value of the property directly into the backing field without invoking the setters. Prior to C# 6.0, we used to create read only properties by creating a private setter and then setting the value in the constructor. However in C#6.0, using the auto-property initializer, a read only property can be easily created as shown in the listing below:

image

Read the full article on the Infragistics blog

Simplifying the Liskov Substitution Principle of SOLID in C#

Before I start writing this article, I want to thank Steve Smith for his great course on the same topic with Pluralsight. This post is inspired by that course.

Read full article on the Infragistics blog here

The Liskov Substitution Principle says that the object of a derived class should be able to replace an object of the base class without bringing any errors in the system or modifying the behavior of the base class.

In short: if S is subset of T, an object of T could be replaced by object of S without impacting the program and bringing any error in the system. Let’s say you have a class Rectangle and another class Square. Square is as Rectangle, or in other words, it inherits the Rectangle class. So as the Liskov Substitution principle states, we should able to replace object of Rectangle by the object of Square without bringing any undesirable change or error in the system.

Let’s take a closer look at this principle with some examples.

Understanding the problem

Let us say we have two classes, Rectangle and Square. In this example, the Square class inherits the Rectangle class. Both classes are created as listed below:

image

The Square class inherits the Rectangle class and overrides the properties as shown in the listing below:

image

Read full article on the Infragistics blog here

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.

Property Initializers in C-Sharp 6.0

In the C-Sharp 3.0 a new feature Automatic property got introduced. It allows us to create a class as a bag of the setters and the getters. You can create a class as follows:


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

    }

Each property is backed by a backing filed. When you set value of the property, setter gets executed to set the value of the backing field. Now catch is that to create a read only property you have to invoke the setter in the constructor of the class and make set as private

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

        public Product()
        {
            Price  = 10;
        }

    }

In the above class definition the Price property is read only and set to the default value 10 and you can set the value of the name property outside the class.

To create a read only property with the default value, we created a private setter and then set the default value in the constructor. In c-sharp 6.0, you can directly create a read only property with default value without invoking the setter. This feature of C# 6.0 is called Property Initializers

Property Initializer allows you to create a property with the default value without invoking the setter. It directly sets value if the backing field.

image

As you see in the above snippet we are setting the default value of Price property as 10. However after creating the instance of the class. Value of price property can be changed. If you wish you can create read only property by removing the setter.

image

Since setter is optional, it is easier to create immutable properties. For your reference source code harnessing Property Initializer is given below:


using System;
namespace demo1
{
    class Program
    {
        static void Main(string[] args)
        {
            Product p = new Product
            {
                
                Name = "Pen"

            };

            Console.WriteLine(p.Price);

            Console.ReadKey(true);
        }
    }

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


We can summarize this post discussing purpose of the auto property initializer. It allows us to create immutable property with the user defined default value. Now to create properties with default values, you don’t have to invoke setter.

Happy coding.

Exception Filters in C-Sharp 6.0

So far we deal with the Exceptions as below. As you see in the following code snippet, we are catching the exception and displaying the error message.


using System;
namespace demo1
{
    class Program
    {
        static void Main(string[] args)
        {

            int number = 24;
            try
            {

                int rem = number % 0;
                Console.WriteLine(rem);
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey(true);
        }
    }
}


Challenge in the above snippet is that you cannot apply filter to the exception. Of course you can have if-else statement inside the try catch block but it will cause a particular catch block to get executed and then filter would get applied.

In C# 6.0 a new feature got introduced to apply filter at the catch block. This feature is known as Exception filters. Now a particular catch block can be executed only of the filter is set to true.

image

In the above snippet we are filtering the exception on the various basis like if message contains a particular string then execute a particular catch block or on the basis of the exception source execute a particular catch block.

This feature may be useful in the scenarios in which, you need to perform various actions on if a condition is met in a particular exception type.

For your reference the source code is given below,

using System;
namespace demo1
{
    class Program
    {
        static void Main(string[] args)
        {

            int number = 24;
            try
            {

                int rem = number % 0;
                Console.WriteLine(rem);
            }
            catch (DivideByZeroException ex) if (ex.Message.Contains("dj"))
            {
                Console.WriteLine(ex.Message);
            }
            catch(DivideByZeroException ex) if (ex.Source == "demo1")
            {
                Console.WriteLine(ex.Source);
            }

            Console.ReadKey(true);
        }
    }
}


Exception message does not contain any string dj hence the first catch block will not get executed. However second catch block will be executed since source of the exception is demo1. You will get the expected output as below:

image

I hope concept of Exception filter is clear to you now and you will harness C# 6.0 feature in your project.

Happy coding

Decorator Pattern in C#

Read full article on Falafel blog

Decorator pattern attach additional functionalities or responsibilities to an existing object at the runtime”. It adds new behaviour to an individual object without affecting other objects of the same class. New behaviour or functionalities can be either added dynamically at the run time or statically.

image

The decorator pattern:

  • · Adds new functionality or behaviour
  • · Either at run time or statically
  • · Without affecting other objects of the class
  • Why do we need this pattern?

    To understand, let us consider a Student object with the basic responsibility to handle and print information like name, age, and grade etc.

    Now you have a requirement to add functionality to maintain lab reports for Science students. How will you do this? Maybe extend the Student class to create a ScienceStudent subclass for this responsibility. Good enough.

Read full article on Falafel blog

Implement Step-by-Step Generic Repository Pattern in C#

Read full article on Falafel blog

It is not a good idea to access the database logic directly in the business logic. Tight coupling of the database logic in the business logic make applications tough to test and extend further. Direct access of the data in the business logic may cause problems such as

  1. Difficulty completing Unit Test of the business logic
  2. Business logic cannot be tested without the dependencies of external systems like database
  3. Duplicate data access code throughout the business layer

Without a Repository, an application will be seen as below:

image

Repository Pattern separates the data access logic and maps it to the entities in the business logic. It works with the domain entities and performs data access logic. In the Repository pattern, the domain entities, the data access logic and the business logic talk to each other using interfaces. It hides the details of data access from the business logic. In other words, business logic can access the data object without having knowledge of the underlying data access architecture. For example, in the Repository pattern, business logic is not aware whether the application is using LINQ to SQL or ADO.NET Entity Model ORM. In the future, underlying data sources or architecture can be changed without affecting the business logic.

Read full article on Falafel blog

Using AutoMapper : Getting Started

Read full article on Falafel blog

I have often seen developers use the LINQ SELECT statement to create a new instance of one class from an existing instance of another class. There are many scenarios when you may have to do this, for example:

  • Creating the domain class instance from the entity class instance
  • Creating the DTO class instance from the entity class instance
  • Creating the POCO class instance from the entity class instance etc.

To do this, developers often use the select statement or manually convert a class object to another class object. Let’s look at an example:

Read full article on Falafel blog