this used implicitly and explicitly to refer to members of an object. - CSharp Custom Type

CSharp examples for Custom Type:this

Description

this used implicitly and explicitly to refer to members of an object.

Demo Code



using System;/* ww  w .ja v a 2 s  .c  om*/

class MainClass
{
   static void Main()
   {
      var time = new MyTime(15, 30, 19);
      Console.WriteLine(time.BuildString());
   }
}

public class MyTime
{
   private int hour; // 0-23
   private int minute; // 0-59
   private int second; // 0-59

   public MyTime(int hour, int minute, int second)
   {
      this.hour = hour; // set "this" object's hour instance variable
      this.minute = minute; // set "this" object's minute
      this.second = second; // set "this" object's second
   }

   public string BuildString() =>
      $"{"this.ToUniversalString()",24}: {this.ToUniversalString()}" +
      $"\n{"ToUniversalString()",24}: {ToUniversalString()}";

   public string ToUniversalString() => $"{this.hour:D2}:{this.minute:D2}:{this.second:D2}";
}

Result


Related Tutorials