Implicit Conversion Operator C# with Example



Implicit 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 implicit operator string(Time operand)
			{
				return string.Format("{0}:{1}", operand.hour, operand.minute);
			}
			
			public static implicit operator int(Time operand)
			{
				return operand.hour * 60 + operand.minute;
			}			
		}

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

0 Comment's

Comment Form

Submit Comment