- narrowing conversion - prohibited.
- widening conversion - allowed.
Ways to Perform Explicit Conversion
- System.Convert - bet. types that impl. IConvertible interface.
- (type) - cast operator - bet. types that define conversion operators.
Boxing/Unboxing
- boxing - converts a value type to ref type. (e.g. convert int -> Object)
- unboxing - ref -> value.
- boxing/unboxing - incur overheads.
- boxing - occurs on calling virtual mthds that structure inherits from System.Object - e.g. ToString().
- Best Practices:
1. Impl. overloads for mthds that accept mult. value types. Better to create mult. overloads than 1 proc taking Object. - 2. Use generics instead of accpeting Object args.
- 3. Override ToString, Equals, GetHash virtual members when defining structures.
How to Implement Conversion in Custom Types
- conversion operators - for narrowing ( k'word explicit)/widening (k'word implicit) conversions bet. numeric types.
- Override ToString() to provide conversion to strings, and override Parse() to provide conversion from strings.
No comments:
Post a Comment