Format data in ToString method. : ToString « Class Interface « C# / C Sharp






Format data in ToString method.

Format data in ToString method.




using System;

public class Time1
{
   private int hour; 
   private int minute; 
   private int second;

   public void SetTime( int h, int m, int s )
   {
      hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); 
      minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); 
      second = ( ( s >= 0 && s < 60 ) ? s : 0 ); 
   } 
   public string ToUniversalString()
   {
      return string.Format( "{0:D2}:{1:D2}:{2:D2}", hour, minute, second );
   } 
   public override string ToString()
   {
      return string.Format( "{0:D2}:{1:D2}:{2:D2} {3}",
         ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
         minute, second, ( hour < 12 ? "AM" : "PM" ) );
   } 
}
public class MemberAccessTest
{
   public static void Main( string[] args )
   {
      Time1 time = new Time1(); 

      time.hour = 7; // error: hour has private access in Time1
      time.minute = 15; // error: minute has private access in Time1
      time.second = 30; // error: second has private access in Time1
   }
} 
 
       








Related examples in the same category

1.demonstrates overriding the ToString() method to provide a custom string outputdemonstrates overriding the ToString() method to provide a custom string output
2.Illustrates how to override the ToString() methodIllustrates how to override the ToString() method
3.Demonstrate ToString()Demonstrate ToString()
4.class declaration maintains the time in 24-hour format and ToString Methodclass declaration maintains the time in 24-hour format and ToString Method
5.Overriding the ToString() MethodOverriding the ToString() Method
6..NET Frameworks Overview:Custom Object Formatting.NET Frameworks Overview:Custom Object Formatting