Posts

Polymorphism in practice (C# sample)

One of the main principles of the Object Oriented Programming is the Polymorphism. This term simply means that an class can be used as more than one type through inheritance. It can have it’s own type, the base type or interface type it inherits from. In C# every type is polymorphic as the all types inherit from Object type.

Lets assume we are building an Internet store with the basket functionality. By creating base class and inheriting from it we get all properties from the base class plus the properties of the class that we are creating. By marking class as abstract we specify that this class cannot be instantiated and may serve only as a base class for other classes deeper in the system.

  public abstract class BasketBase
  {

  }

   public class Basket : BasketBase
   {

   }

By marking methods as a virtual in the base class, we can implement our own logic whenever we need it using override keyword in the underlying class.

   public abstract class BasketBase
   {
        public List<ProductItem> ProductList = new List<ProductItem>();
        public double Total = 0;
        public bool IsCheckedOut = false;
        public abstract void Checkout();
    }

    public class Basket : BasketBase
    {
        public override void Checkout()
        {
            if (base.IsCheckedOut) { throw new Exception("Check out has been already done!"); };
            ////////////

            foreach (ProductItem p in base.ProductList)
            {
                base.Total += p.ProductPrice * p.ItemCount;
            }

            base.IsCheckedOut = true;
        }
     }

When building advanced systems, Polymorphism gives you the chance to easily change the logic of existing methods by overriding it. It also makes your application cleaner by reusing amount of code needed to create properties in underlying classes.

I have included sample application of the Internet store with the basket and voucher functionality for you to do some testing.


basket.vouchers
Polymorphism-sample-app

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...