elena1234

CarSalesman- class Car (How to override ToString())

Feb 8th, 2021 (edited)
623
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. using System.Text;
  2.  
  3. namespace CarSalesman
  4. {
  5.     public class Car
  6.     {
  7.         public Car(string model, Engine engine)
  8.         {
  9.             this.Model = model;
  10.             this.Engine = engine;
  11.             this.Weight = null;
  12.             this.Color = "n/a";
  13.         }
  14.         public Car(string model, Engine engine, int weight)
  15.          : this(model, engine)
  16.         {
  17.             this.Weight = weight;
  18.         }
  19.  
  20.         public Car(string model, Engine engine, string color)
  21.         : this(model, engine)
  22.         {
  23.             this.Color = color;
  24.         }
  25.  
  26.  
  27.         public Car(string model, Engine engine, int weight, string color)
  28.             : this(model, engine)
  29.         {
  30.             this.Weight = weight;
  31.             this.Color = color;
  32.         }
  33.  
  34.         public string Model { get; set; }
  35.         public Engine Engine { get; set; }
  36.         public int? Weight { get; set; }
  37.         public string Color { get; set; }
  38.  
  39.         public override string ToString()
  40.         {
  41.             var sb = new StringBuilder();
  42.             sb.AppendLine($"{this.Model}:");
  43.             sb.AppendLine($"  {this.Engine.Model}:");
  44.             sb.AppendLine($"   Power: {  this.Engine.Power}");
  45.             if (this.Engine.Displacement == null)
  46.             {
  47.                 sb.AppendLine("   Displacement: n/a");
  48.             }
  49.  
  50.             else
  51.             {
  52.                 sb.AppendLine($"   Displacement: {this.Engine.Displacement}");
  53.             }
  54.  
  55.             sb.AppendLine($"   Efficiency: {this.Engine.Efficiency}");
  56.             if (this.Weight == null)
  57.             {
  58.                 sb.AppendLine("  Weight: n/a");
  59.             }
  60.  
  61.             else
  62.             {
  63.                 sb.AppendLine($"  Weight: {this.Weight}");
  64.             }
  65.  
  66.             sb.AppendLine($"  Color: { this.Color}");
  67.             return sb.ToString().Trim();
  68.         }
  69.     }
  70. }
  71.  
Add Comment
Please, Sign In to add comment