Conversion Operators
Conversion operators convert an object from one type to another type. Conversion operators can be implicit or explicit. Implicit conversion operators do not require a type cast to be specified in source code to perform the conversion. Explicit conversion operators require a type cast be present in the source code to perform the conversion.
The following signature shows the Point class's explicit conversion operator for converting between a Point and a Size.
[Visual Basic]
Public Shared Function op_Explicit( _
ByVal p As Point _
) As Size
[C#]
public static Size op_Explicit(
Point p
);
Ideally, customer research data should exist to support defining a conversion operator. Alternatively, support for defining the operator could be in the form of examples where one or more similar types need such a conversion.
For example, Int32, Double, and Decimal are all numeric types, while DateTime is not. Converting a Double type to a DateTime type should not be implemented as a conversion operator. Use a constructor to convert a type to another type that is not in the same domain.
For example, there should not be an implicit conversion from Double to Single because Double has a higher precision than a Single. An explicit conversion operator can be provided for lossy conversions.
Implicit casts are called by the system; the user might not be aware that a conversion is taking place and will have difficulty debugging the code.
Do throw System.InvalidCastException if a call to a cast operator results in a lossy conversion and the contract of the operator does not allow lossy conversions.
Portions Copyright 2005 Microsoft Corporation. All rights reserved.
Portions Copyright Addison-Wesley Corporation. All rights reserved.
For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.
Member Design Guidelines
Design Guidelines for Developing Class Libraries