CHAPTER 23

image

Custom Conversions

This chapter covers how to define custom type conversions for an object. As can be seen in the example below, there is a class called MyNum with a single int field and a constructor. With a custom type conversion, it is possible to allow an int to be implicitly converted to an object of this class.

class MyNum{   public int val;  public MyNum(int i) { val = i; }} 

Implicit conversion methods

For this to work an implicit conversion method needs to be added to the class. This method’s signature looks similar to that used for unary operator overloading. It must be declared as public static and includes the operator ...

Get C# Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.