Create auto properties and access its value - CSharp Custom Type

CSharp examples for Custom Type:Property

Description

Create auto properties and access its value

Demo Code



using System; // namespace containing ArgumentOutOfRangeException

public class Time1
{
   public int Hour { get; set; } // 0 - 23
   public int Minute { get; set; } // 0 - 59
   public int Second { get; set; } // 0 - 59

   public void SetTime(int hour, int minute, int second)
   {/*from w ww. j  ava  2s .c o  m*/
      if ((hour < 0 || hour > 23) || (minute < 0 || minute > 59) ||
         (second < 0 || second > 59))
      {
         throw new ArgumentOutOfRangeException();
      }

      Hour = hour;
      Minute = minute;
      Second = second;
   }

   // convert to string in universal-time format (HH:MM:SS)
   public string ToUniversalString() =>
      $"{Hour:D2}:{Minute:D2}:{Second:D2}";

   // convert to string in standard-time format (H:MM:SS AM or PM)
   public override string ToString() =>
      $"{((Hour == 0 || Hour == 12) ? 12 : Hour % 12)}:" +
         $"{Minute:D2}:{Second:D2} {(Hour < 12 ? "AM" : "PM")}";
}
class Time1Test
{
   static void Main()
   {
      var time = new Time1(); // invokes Time1 constructor

      Console.WriteLine($"The initial universal time is: {time.ToUniversalString()}");
      Console.WriteLine($"The initial standard time is: {time.ToString()}");
      Console.WriteLine(); // output a blank line

      time.SetTime(13, 27, 6);
      Console.WriteLine($"Universal time after SetTime is: {time.ToUniversalString()}");
      Console.WriteLine($"Standard time after SetTime is: {time.ToString()}");
      Console.WriteLine(); // output a blank line

      // attempt to set time with invalid values
      try
      {
         time.SetTime(99, 99, 99);
      }
      catch (ArgumentOutOfRangeException ex)
      {
         Console.WriteLine(ex.Message + "\n");
      }

      // display time after attempt to set invalid values
      Console.WriteLine("After attempting invalid settings:");
      Console.WriteLine($"Universal time: {time.ToUniversalString()}");
      Console.WriteLine($"Standard time: {time.ToString()}");
   }
}

Result


Related Tutorials