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

Keep your code DRY

Other day my Boss was reviewing the code written by me. He had a feedback, keep the code DRY. It was great feedback, and I thought why not to share with you that what does DRY mean?

DRY stands for Do not Repeat Yourself.

clip_image002

To understand it better let is consider below code snippet:

clip_image003

I am fetching a particular movie on basis of the id. As you notice this code is inside Details method. Next in another method Edit in the controller and I am doing the same fetching a particular movie on basis of the id as shown below:

clip_image004

As you clearly notice that I am repeating the code in the same class hence CODE IS NOT DRY in above scenario. The code should not be repeated and should be kept in repository class. We could have a function FindById() in MovieRepository class and both the methods will call FindById(). A common function to find the movie by id can be created as follows:

clip_image006

And then both methods of Controllers can use them as follows:

clip_image007

In the layered architecture approach DRY code is very essential for robust software development. I hope now you have better understanding of having code DRY and you will follow this approach.

Happy Coding.