One of my many jobs here at MS is helping out with the .NET Framework Design Guidelines Document.  Tonight I had to make a small tweak to a guideline I added last week so I thought while I was in there I would post it here to see if folks had comments.

 

-----------------------------------------------------------------------------

 

7.10 Conversion Operators

  • Do not define cast operators in publicly exposed APIs.  The exception to this rule is for creating “primitive” types such as Int32, Double, or DateTime.
  • Do not define casting operators outside of a types domain – for example Int32, Double, and Decimal are all numeric types – while DateTime is not.  Therefore there should be no cast operator to go from a Double to a DateTime.  A constructor is preferred in this case. 
  • Do not use cast operators in a surprising way.  That is only provide them where there is a strong expectation that they would be there and ideally some prior art that justifies them.
  • Do not lose precision in implicit casts.
  • For example, there should not be an implicit cast from Double to Int32, but there may 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.
  • Do provide casts that operate on the whole object. The value that is cast represents the whole value being cast, not one sub part. 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 Time or TimeSpan into an Int. The Int still represents the time or duration. It does not make sense to convert a file name string such as, "c:\mybitmap.gif" into a Bitmap object.
  • Do cast values that are in the same domain. Do not cast values from different domains.  Casts operate within a particular domain of values. For example, numbers and strings are different domains. So it makes sense that an Int32 can cast to a Double. It does not make sense for an Int to cast to a String, because they are in different domains.