Blog

Filter posts by Category Or Tag of the Blog section!

Liskov substitution principle with sample in C#

Sunday, 16 September 2012

Liskov substitution principle (LSP) is a simple pattern in object-oriented programming, notice about definition If A is a subtype of B, then object of B could be replaced with an object of A, in another definition subclass can behave like base class. maybe you are using it for years, take a look at  the example:

 

    public class BaseClass
    {
        public string ProductName { get; set; }
        public virtual void Shipping()
        {
            //
        }

        public virtual void Order()
        {
            //
        }
     }

 

 and about the derived class called DerivedClass 

 

    public class DerivedClass :BaseClass
    {
        public string CustomerInfo { get; set; }
        public void DeliveryAddress()
        {
            //
        }
        public override void Shipping()
        {
            base.Shipping();
        }

        public override void Order()
        {
            base.Order();
        }
    }

 

It's clear that derived class override the virtual methods of the base class, and can be used In derived class objects, see the usage

 

    public class Present
    {
        public static void Main()
        {
            var baseClass = new DerivedClass();
            baseClass.ProductName = "Vibrator";
            baseClass.Shipping();
            baseClass.Order();
        }
    }

 

comments powered by Disqus