In this article, I am going to share with you about User-Defined Conversion in C#.
User-Defined Conversion
In C# programming, a situation may arise when we have to convert a data type into our own custom type or vice-versa. The custom type may be any class, object, or struct that we created. To perform these types of special conversions, we have to define a special method. The syntax of these special methods is shown below.
- static public implicit/explicit operator ConvertToType(ConvertFromDataType value)
- {
-
- return ConvertToType;
- }
Here, in the above method, 'ConvertFromDataType' is the data type we are going to change and 'ConvertToType' will be the converted type. We use implicit or explicit depending on the situation. The return type of this method should be of Converted type. Understand the below example to have more clarity around it.
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- class Student
- {
- public string Name { get; set; }
- public int Roll_No { get; set; }
-
-
- static public implicit operator Student(int value)
- {
-
- return new Student { Name = "jainy", Roll_No = value };
- }
-
-
- static public explicit operator int(Student student)
- {
-
- return student.Roll_No;
- }
- }
-
- static void Main(string[] args)
- {
-
- Student student = new Student();
- int value = 100;
-
-
- student = value;
- Console.WriteLine("Student name" + student.Name + " Student Roll No." + student.Roll_No);
-
-
- value = student.Roll_No;
- Console.WriteLine("Roll No. " + value);
-
-
- value = (int)student;
- Console.WriteLine("Roll No. " + value);
- Console.ReadKey();
- }
- }
- }
In this example, we have created a class named 'Student' which contains two property members 'Name' and 'Roll_No'. We have also written two special conversion methods to convert from type 'Student' to type 'int' and vice-versa.
The conversion from "int" to "Student" can be performed directly. As we are converting from smaller to larger data types, so we use implicit on method definition, while the conversion from 'Student' to 'int' requires a cast operator as we are converting from larger to smaller type and we use explicit on method definition.
In 'Main' method, we have directly assigned an int value to Student type without compiling for errors due to the method defined above otherwise, an error will produce as "Cannot implicitly convert type 'int' to 'Tutpoint.Program.Student'". The same happens for conversion from "student" to "int" type.