Advertisement
karlakmkj

Constructor

Nov 23rd, 2020 (edited)
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. //In Forest.cs
  2.  
  3. using System;
  4.  
  5. namespace BasicClasses
  6. {
  7.   class Forest
  8.   {
  9.     //Fields
  10.     public int age;
  11.     private string biome;
  12.  
  13.     //Constructor
  14.     public Forest(string name, string biome){
  15.       Name = name;  //set the Name property
  16.       Biome = biome;    //set the Biome property
  17.       Age = 0;
  18.     }
  19.    
  20.     //Properties
  21.     public string Name
  22.     { get; set; }
  23.    
  24.     public int Trees
  25.     { get; set; }
  26.    
  27.     public string Biome
  28.     {
  29.       get { return biome; }
  30.       set
  31.       {
  32.         if (value == "Tropical" || value == "Temperate" || value == "Boreal")
  33.         {
  34.           biome = value;
  35.         }
  36.         else
  37.         {
  38.           biome = "Unknown";
  39.         }
  40.       }
  41.     }
  42.    
  43.     public int Age
  44.     {
  45.       get { return age; }
  46.       private set { age = value; }
  47.     }
  48.    
  49.     //Methods
  50.     public int Grow()
  51.     {
  52.       Trees += 30;
  53.       Age += 1;
  54.       return Trees;
  55.     }
  56.    
  57.     public int Burn()
  58.     {
  59.       Trees -= 20;
  60.       Age += 1;
  61.       return Trees;
  62.     }
  63.    
  64.   }
  65. }
  66. ============================================================================================================================
  67. //In Program.cs file
  68. using System;
  69.  
  70. namespace BasicClasses
  71. {
  72.   class Program
  73.   {
  74.     static void Main(string[] args)
  75.     {
  76.      
  77.       Forest f = new Forest("Congo", "Desert" ); //call the constructor by writing variable values as the arguments
  78.      
  79.       f.Trees = 0;  
  80.       /* Hence we can delete
  81.         f.Name = "Congo";
  82.         f.Biome = "Desert";
  83.       as the lines are not needed  
  84.       */
  85.  
  86.       Console.WriteLine(f.Name);
  87.       Console.WriteLine(f.Biome);
  88.      
  89.     }
  90.   }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement