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.