Tuesday, 12 September 2017

Simple extension class in ASP.NET C# application

We are going to write simple extension class to automatically add tax and give us gross price for net price. Very common feature in most of applications that are dealing with accounting, finance, trading, e commerce etc.

Seing code like this in lots of different places in application is not uncommon.

decimal grossPrice = (etPrice * 0.20) + netPrice;

It is not the end of the world if you are using that only in one place of the application, but in most case this code might appear in many places. As a developer I hate magic number (0.20 in this case) and not using DRY (do not repeat yourself) approach.

There is very simple approach to this problem I like to use - using extension.

Let's get straight to the code.

Constant class
public static class TaxConstants
  {
    public static decimal TAX_VALUE = (decimal)0.20;
  }

Extension class

namespace AbDeveloper.Extensions

public static class PriceExtension
  {
    public static decimal AddTaxToNetValue(this decimal price)
    {
      return price + price * Constants.TaxConstants.TAX_VALUE;
    }
  }


We can now easily test the functionality in test project.

using namespace AbDeveloper.Extensions;

[TestClass]
  public class PriceExtensionTest
  {
    [TestMethod]
    public void TestAddTaxToNetValue()
    {
      decimal netPrice = 20;
      decimal grossPrice = netPrice.AddTaxToNetValue();

      Assert.AreEqual(24, grossPrice, "Expected gross price is incorrect. Check AddTaxToNetValue method in PriceExtension class.");
    }
  }



At this stage test will pass and grossPrice will be equal 24 with an input of 20. If however tax rate will change to 0.25 (25%) test will fail.

In order to use extension in class make sure you will add "using namespace" expression.