|
| 1 | +using System; |
| 2 | +using Systemm.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | +using System.IO; |
| 5 | +using System.Linq; |
| 6 | +using System.Text; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using static System.Console; |
| 9 | + |
| 10 | +namespace DesignPrinciples |
| 11 | +{ |
| 12 | + public class Rectangle |
| 13 | + { |
| 14 | + public virtual int Width { get; set; } |
| 15 | + public virtual int Height { get; set; } |
| 16 | + |
| 17 | + //Overloaded Constructors |
| 18 | + public Rectangle() |
| 19 | + { |
| 20 | + |
| 21 | + } |
| 22 | + |
| 23 | + publice Rectangle(int width, int height) |
| 24 | + { |
| 25 | + Width = width; |
| 26 | + Height = height; |
| 27 | + } |
| 28 | + |
| 29 | + //Formats the return text |
| 30 | + public override string ToString() |
| 31 | + { |
| 32 | + return $"{nameof(Width)}: {Width}, {nameof(Height)}: {Height}"; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + //Created below is a Square class that seems workable and will sometimes get the results you want... |
| 37 | + //..but! Because the way that Square inherited from rectangle means you cannot substitute the Rectangle for the Square |
| 38 | + // without running into errors when you reset just the width or height on the rectangle |
| 39 | + //You must make the properties of the Rectangle above virtual so you can override them in the square class |
| 40 | + public class Square : Rectangle |
| 41 | + { |
| 42 | + public override int Width |
| 43 | + { |
| 44 | + set |
| 45 | + { |
| 46 | + base.Width = base.Height = value; |
| 47 | + } |
| 48 | + } |
| 49 | + public override int Height |
| 50 | + { |
| 51 | + set |
| 52 | + { |
| 53 | + base.Width = base.Height = value; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + #region Description of Principle |
| 59 | + //Liskov Substitution is the "L" in the SOLID principles of OOP attributed to Barbara Liskov of MIT |
| 60 | + // Object Oriented Programming Principle stating that in a computer program that 2 objects in |
| 61 | + //a subtype can be substituted without altering any type of the desirable properties of the program |
| 62 | + #endregion |
| 63 | + |
| 64 | + public class LiskovSubstitution |
| 65 | + { |
| 66 | + //Lambda operator returning value of the area |
| 67 | + |
| 68 | + static public int Area(Rectangle r) => r.Width * r.Height; |
| 69 | + |
| 70 | + public static void Main(string[] args) |
| 71 | + { |
| 72 | + Rectangle rc = new Rectangle(); |
| 73 | + WriteLine($"{rc} has area { Area(rc)}"); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments