Advertisement
DEMcKnight

Property and Field examples

Feb 9th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.86 KB | None | 0 0
  1. class TimePeriod
  2. {
  3.     //Private seconds field
  4.     private double _seconds;
  5.    
  6.     //Public Seconds property
  7.     public double Seconds
  8.     {
  9.         get { return _seconds; }
  10.         set { _seconds = value; }
  11.     }
  12.    
  13.     //Public Minutes property
  14.     public double Minutes
  15.     {
  16.         get { return _seconds / 60; }
  17.         set { _seconds = value * 60; }
  18.     }
  19.    
  20.     //Public Hours property
  21.     public double Hours
  22.     {
  23.         get { return _seconds / 3600; }
  24.         set { _seconds = value * 3600; }
  25.     }
  26. }
  27.  
  28. //Usage example
  29.  
  30. class Program
  31. {
  32.     static void Main()
  33.     {
  34.         TimePeriod t = new TimePeriod();
  35.  
  36.         // Assigning the Hours property causes the 'set' accessor to be called.
  37.         t.Hours = 24; //sets the _seconds field
  38.  
  39.         // Evaluating the Hours property causes the 'get' accessor to be called.
  40.         System.Console.WriteLine("Time in hours: " + t.Hours);
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement