SoFunction
Updated on 2025-03-08

C# Custom Type Casting Instance Analysis

This article describes the usage of C# custom type casting. Share it for your reference. The specific analysis is as follows:

Let me give you a small example

Class definition:

public class MyCurrency
{
  public uint Dollars;
  public ushort Cents;
  public MyCurrency(uint dollars, ushort cents)
  {
     = dollars;
     = cents;
  }
  public override string ToString()
  {
    return (
      "${0}.{1}", Dollars, Cents
    );
  }
  //Provide implicit conversion from MyCurrency to float  public static implicit operator float(MyCurrency value)
  {
    return  + ( / 100.0f);
  }
  //Convert float to MyCurrency cannot guarantee that the conversion will be successful, because float can  //Storage negative values, while MyCurrency can only store positive numbers  //Float stores orders of magnitude larger than uint. If float contains a value larger than unit,  //The unexpected result will be obtained, so it must be defined as an explicit conversion  //Float to MyCurrency display conversion  public static explicit operator MyCurrency(float value)
  {
    //Checked must be added here. If you add it outside the calling function, you will not report an error.    //Because the overflow exception occurs in the code of the cast operator    //Convert.ToUInt16 is to prevent loss of accuracy    //This paragraph is very important. Please refer to "C# Advanced Programming (Chinese Seventh Edition) Page 218 Description" for details.    {
      uint dollars = (uint)value;
      ushort cents = Convert.ToUInt16((value - dollars) * 100);
      return new MyCurrency(dollars, cents);
    }
  }
}

Test code:

private void btn_Test custom type cast_Click(object sender, EventArgs e)
{
  MyCurrency tmp = new MyCurrency(10, 20);
  //Call the implicit conversion of MyCurrency to float  float fTmp = tmp;
  (());
  float fTmp2 = 200.30f;
  //Call float to MyCurrency's display conversion  MyCurrency tmp2 = (MyCurrency)fTmp2;
  (());
}

I hope this article will be helpful to everyone's C# programming.