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
);

Do not provide a conversion operator if such conversion is not clearly expected by the end users.

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.

Do not define conversion operators outside of a type’s domain.

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.

Do not provide an implicit conversion operator if the conversion is potentially lossy.

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.

Do not throw exceptions from implicit casts.

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.

See Also

Other Resources

Member Design Guidelines

Design Guidelines for Developing Class Libraries