SoFunction
Updated on 2025-03-06

Methods for implicit conversion of custom types by implicit keyword

Implicit conversions can improve the readability of source code by eliminating unnecessary type conversions. However, because implicit conversion does not require the programmer to explicitly cast a type,

It is another type, so you must be extra careful when using implicit conversions to avoid unexpected results. In general, the implicit conversion operator should never throw an exception and

Never lose information so that they can be used safely without the programmer's knowledge.

In C#, the implicit keyword can be used to perform implicit conversions of custom types. Here is an example to illustrate.

Define a Point class to represent a point:

Copy the codeThe code is as follows:

public class Point
  {
    public double X { get; set; }
    public double Y { get; set; }
  }

Then define a static method in the Point class to implicitly convert from a string to a Point type:

public class Point
 {
  public double X { get; set; }
  public double Y { get; set; }
  public static implicit operator Point(string constValue)
  {
   var result = new Point();
   try
   {
    var arPoint = (new[] {","}, );
     = (arPoint[0]);
     = (arPoint[1]);
   }
   catch
   {
     = 0;
     = 0;
   }
   return result;
  }
 }

The process of using is very simple, just like our usual implicit conversion:   

Copy the codeThe code is as follows:

Point p = "3,4.5";
      ("X:{0}, Y:{1}", , );

Note that you should try to avoid errors during the implicit conversion process, or you can handle exceptions. Otherwise, use explicit to cast.

The above is the method of implicit conversion of custom types by implicit keywords. I hope it will be helpful to everyone.