Invoice class implements IPayable. - CSharp Custom Type

CSharp examples for Custom Type:interface

Description

Invoice class implements IPayable.

Demo Code



using System;//  w  w  w. j  a v a2  s.  c  o  m
using System.Collections.Generic;
public class Invoice : IPayable
{
    public string PartNumber { get; }
    public string PartDescription { get; }
    private int quantity;
    private decimal pricePerItem;

    public Invoice(string partNumber, string partDescription, int quantity, decimal pricePerItem)
    {
        PartNumber = partNumber;
        PartDescription = partDescription;
        Quantity = quantity; // validate quantity
        PricePerItem = pricePerItem; // validate price per item
    }

    public int Quantity
    {
        get
        {
            return quantity;
        }
        set
        {
            if (value < 0) // validation
            {
                throw new ArgumentOutOfRangeException(nameof(value),
                   value, $"{nameof(Quantity)} must be >= 0");
            }

            quantity = value;
        }
    }

    public decimal PricePerItem
    {
        get
        {
            return pricePerItem;
        }
        set
        {
            if (value < 0) // validation
            {
                throw new ArgumentOutOfRangeException(nameof(value),
                   value, $"{nameof(PricePerItem)} must be >= 0");
            }

            pricePerItem = value;
        }
    }

    public override string ToString() =>
       $"invoice:\npart number: {PartNumber} ({PartDescription})\n" +
       $"quantity: {Quantity}\nprice per item: {PricePerItem:C}";

    public decimal GetPaymentAmount() => Quantity * PricePerItem;
}

public interface IPayable
{
    decimal GetPaymentAmount(); // calculate payment; no implementation
}




class MainClass
{
    static void Main()
    {
        var payableObjects = new List<IPayable>() {
         new Invoice("0", "seat", 2, 35.00M),
         new Invoice("2", "tire", 4, 79.95M) };

        Console.WriteLine("Invoices and Employees processed polymorphically:\n");

        foreach (var payable in payableObjects)
        {
            Console.WriteLine($"{payable}");
            Console.WriteLine($"payment due: {payable.GetPaymentAmount():C}\n");
        }
    }
}

Result


Related Tutorials