Advertisement
karlakmkj

Properties - getter & setter

Nov 23rd, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. //Creating Property for fields - getter & setter method
  2.  
  3. //In Forest.cs file
  4. using System;
  5.  
  6. namespace BasicClasses
  7. {
  8.   class Forest
  9.   {
  10.     public string name;
  11.     public int trees;
  12.     public int age;
  13.     public string biome;
  14.    
  15.     //Property for name field
  16.     public string Name {
  17.       get {return name;}
  18.       set {name = value;}
  19.     }
  20.  
  21.     //Property for trees field
  22.     public int Trees {
  23.       get {return trees;}
  24.       set {trees = value;}
  25.     }
  26.  
  27.     //Property for biome field
  28.     public string Biome {
  29.       get {return biome;}
  30.       set {
  31.         if (value == "Tropical" || value == "Temperate" || value == "Boreal")
  32.         {biome = value;}
  33.         else {biome = "Unknown";}        
  34.         }
  35.     }
  36.   }
  37. }
  38. ============================================================================================================================
  39. //In Program.cs file
  40. using System;
  41.  
  42. namespace BasicClasses
  43. {
  44.   class Program
  45.   {
  46.     static void Main(string[] args)
  47.     {
  48.       Forest f = new Forest();
  49.       f.Name = "Congo";  //change field to Property Name
  50.       f.Trees = 3;
  51.       f.age = 0;
  52.       f.Biome = "Tropical";
  53.      
  54.       Console.WriteLine(f.Name); //invoke using Property Name
  55.       Console.WriteLine(f.Trees);
  56.       Console.WriteLine(f.Biome);
  57.  
  58.     }
  59.   }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement