Guidelines for Casting Types

The following rules outline the usage guidelines for casts:

  • Do not allow implicit casts that will result in a loss of precision. For example, there should not be an implicit cast from Double to Int32, but there might be one from Int32 to Int64.
  • Do not throw exceptions from implicit casts because it is very difficult for the developer to understand what is happening.
  • Provide casts that operate on an entire object. The value that is cast should represent the entire object, not a member of an object. For example, it is not appropriate for a Button to cast to a string by returning its caption.
  • Do not generate a semantically different value. For example, it is appropriate to convert a DateTime or TimeSpan into an Int32. The Int32 still represents the time or duration. It does not, however, make sense to convert a file name string such as "c:\mybitmap.gif" into a Bitmap object.
  • Do not cast values from different domains. Casts operate within a particular domain of values. For example, numbers and strings are different domains. It makes sense that an Int32 can cast to a Double. However, it does not make sense for an Int32 to cast to a String, because they are in different domains.

See Also

Design Guidelines for Class Library Developers