CHAPTER 25

image

User-Defined Conversions

C# allows conversions to be defined between classes or structs and other objects in the system. User-defined conversions are always static functions, which must either take as a parameter or return as a return value the object in which they are declared. This means that conversions can’t be declared between two existing types, which makes the language simpler.

A Simple Example

This example implements a struct that stores Roman numerals. It could also be written as a class, but since it acts like a built-in value type, a struct makes more sense.

struct RomanNumeral{    public RomanNumeral(short value)    {

Get A Programmer's Guide to C# 5.0, 4th Edition 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.