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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.