logo
CSharp_Prog_Guide

Результат 1

conversion occurred

Example 2

Description

This example demonstrates an implicit conversion operator by defining a conversion operator that undoes what the previous example did: it converts from a value class called Digit to the integral Byte type. Because any digit can be converted to a Byte, there's no need to force users to be explicit about the conversion.

Code

struct Digit

{

byte value;

public Digit(byte value) //constructor

{

if (value > 9)

{

throw new System.ArgumentException();

}

this.value = value;

}

public static implicit operator byte(Digit d) // implicit digit to byte conversion operator

{

System.Console.WriteLine("conversion occurred");

return d.value; // implicit conversion

}

}

class TestImplicitConversion

{

static void Main()

{

Digit d = new Digit(3);

byte b = d; // implicit conversion -- no cast needed

}

}

Output 2

conversion occurred