Explicit Conversion Operator C# with Example



Explicit Conversion Operator C# with Example

 	using System;

	namespace CSharpClass
	{
		class Time
		{
			byte hour {get; set;}
			byte minute {get; set;}
			
			public Time(){}
			public Time(byte h, byte m)
			{
				this.hour = h;
				this.minute = m;
			}
			
			public static explicit operator string(Time operand)
			{
				return string.Format("{0}:{1}", operand.hour, operand.minute);
			}
			
			public static explicit operator int(Time operand)
			{
				return operand.hour * 60 + operand.minute;
			}			
		}

		class OperatorOverloading
		{
			static void Main()
			{
				Time hmt = new Time(12, 10);
				
				int mins = (int)hmt;
				Console.WriteLine("Total Minutes: " + mins);
				
				string time = (string)hmt;
				Console.WriteLine("Time: " + time);
			}
		}
	} 

0 Comment's

Comment Form

Submit Comment