1. Conversion Operator Introduction
Conversion Operator in C# converts one Type to another type. There are two flavours to it and we should implement both. One is Implicit Conversion and other one is Explicit Conversion. In a class type, we can provide two conversion operators those tells how a class can be casted to other type & how other type can be converted to class type. In this example, we will create a class called TimePart and add a conversion method to convert that to a String. We will also provide a conversion method which converts the String into a TimePart instance.
2. TimePart Members
The below code shows the TimePart class and its members. We also have a constructor to initialize.

Explanation
- The class contains three private integers to represent the time parts Hour, Minute and Seconds.
- The constructor takes three integers and initializes the internal time-part members.
3. Getter Methods
In the below code, we have public methods to access the private TimePart members. Note, the constructor is the only way to initialize the member in our example. We don’t have any setter method in our example.

4. ToString Override
We need a way to represent our TimePart class in string format. Below is the ToString override.
Explanation
- The method we are overriding is the
ToString
and the keyword override denotes it. The ToString method is called whenever we want to print our class in the string format. For example, we can append our class with a String using the ‘+’ operator and print that in console output window. - Our ToString override separates the internal members with a ‘:’ in between. Here we use Format function of the string and provide place holder substitute like {0},{1} and so on.
- The place holders are filled by the Hour, Min, and Sec private members. So, our to string represents the TimePart in Hour:Min:Seconds string format.
5. Implicit Conversion Operator
Our TimePart can be converted to string and below is the conversion method.
Explanation
- Conversion methods should be static and hence we marked the method as static followed by the
implicit operator
keywords. The implicit keyword here enables the implicit conversion likeString str = time_part_instance;
. - We want to convert TimePart as a String and hence the parameter type is TimePart and return type is String.
- Before we do the conversion, we set return value as empty.
- The
Format
function reads the internal members and assigns that to the return string.
6. Explicit Conversion Operator
With explicit conversion operator, we can assign a String to a TimePart instance. The conversion function is shown below:
Explanation
- The keyword
explicit operator
says that we are defining the function for explicit conversion. - Since the conversion is from String to TimePart, the function takes String as a parameter and returns TimePart to the caller.
- The string should be in the HH:MM:SS format. So, inside the body of the operator, we make a call to Split function to have an array of the by-parted string.
- As we need to return the TimePart, we construct the instance of a TimePart.
- The by-parted string array contains Hour, Min and Seconds and we store that in the TimePart instance’s internal members.
- The TimePart instance is returned to the caller. The returned object is a converted instance of TimePart.
7. Using the Conversion Operators
The code below tests how our conversion operators are working.
Explanation
- First, we create the TimePart instance to denote 6 hours, 40 minutes, and 20 seconds. The internal members of the
tp
instance holds these time values. - Here, we assign the TimePart instance to a String variable
StrTimeParts
. Since, we have implicit conversion operator, we will get the time compartments converted into string as return value which will be assigned toStrTimeParts
. Here, thetp
will go as a parameter to our implicit conversion operator. - The converted value is printed and shown in the console output window.
- Next, we store a time in string format in the variable called
time
. - The statement
(TimePart)time
performs the explicit conversion. Here, we attempt to convert a String into TimePart, and it will succeed as we have explicit conversion operator. We know that our explicit conversion operator by-parts the passed-in string and assigns that to the internal members of the TimePart. This code snippet stores the return value in a reference calledtp2
. - We print the TimePart instance in the console window. Note, the statement here does not call the
ToString
function as we have a implicit conversion function. The string concatenation here calls our implicit conversion function and appends the return value with the constant string. - Since the Time formatted string is converted as TimePart, we can easily read the required time part(s) and display it. In our case, we displayed only hours and seconds.
8. Code Reference
8.1 TimePart.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConversionOpr { public class TimePart { //Sample 01: Class Members private int Hour; private int Min; private int Sec; //Sample 02: Constructor public TimePart(int Hour, int Minutes, int Seconds) { this.Hour = Hour; Min = Minutes; Sec = Seconds; } //Sample 03: Getter Methods public int GetHour() { return this.Hour; } public int GetMin() { return this.Min; } public int GetSec() { return this.Sec; } //Sample 04: Represent in String Format public override string ToString() { return string.Format("{0}:{1}:{2}", this.Hour, this.Min, this.Sec); } //Sample 05: Implicit Conversion Operator public static implicit operator String(TimePart timeparts) { String ret = ""; ret = string.Format("{0}:{1}:{2}", timeparts.Hour, timeparts.Min, timeparts.Sec); return ret; } //Sample 06: Explicit Conversion Operator public static explicit operator TimePart(String Time) { string[] parts = Time.Split(':'); TimePart tp = new TimePart(0, 0, 0); tp.Hour = Int32.Parse(parts[0]); tp.Min = Int32.Parse(parts[1]); tp.Sec = Int32.Parse(parts[2]); return tp; } } } |
8.2 Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ConversionOpr; namespace ConversionOpr { class Program { static void Main(string[] args) { //Sample 07: Create Time Parts TimePart tp = new TimePart(6, 40, 20); //Sample 08: Convert Time Parts as String & Print String StrTimeParts = tp; Console.WriteLine("Time is " + StrTimeParts); //Sample 09: Have TimePart as String String time = "10:57:18"; TimePart tp2 = (TimePart)time; Console.WriteLine("Time is " + tp2); //Sample 10: Print By-parted Time Console.WriteLine("Hour " + tp2.GetHour()); Console.WriteLine("Seconds " + tp2.GetSec()); } } } |
Categories: C#
Tags: Explicit Operator Overloading, Implicit Operator Overloading, Operator Overloading