
17 Classes
17.9 Operators
17.9.3 Conversion operators
Paragraph 11 A conversion operator declaration introduces a user-defined conversion (§13.4), which augments the pre-defined implicit and explicit conversions.
Paragraph 21 A conversion operator declaration that includes the implicit keyword introduces a user-defined implicit conversion. 2 Implicit conversions can occur in a variety of situations, including function member invocations, cast expressions, and assignments. 3 This is described further in §13.1.
Paragraph 31 A conversion operator declaration that includes the explicit keyword introduces a user-defined explicit conversion. 2 Explicit conversions can occur in cast expressions, and are described further in §13.2.
Paragraph 41 A conversion operator converts from a source type, indicated by the parameter type of the conversion operator, to a target type, indicated by the return type of the conversion operator. 2 A class or struct is permitted to declare a conversion from a source type S to a target type T provided all of the following are true:
using System;
public struct Digit
{
byte value;
public Digit(byte value) {
if (value < 0 || value > 9) throw new ArgumentException();
this.value = value;
}
public static implicit operator byte(Digit d) {
return d.value;
}
public static explicit operator Digit(byte b) {
return new Digit(b);
}
}
the conversion from Digit to byte is implicit because it never throws exceptions or loses information, but the conversion from byte to Digit is explicit since Digit can only represent a subset of the possible values of a byte. end example]
| |
| Jagger Software Ltd | |
| Company # 4070126 | |
| VAT # 762 5213 42 |