четверг, 11 сентября 2014 г.

Preparing to MS Exam 70-483 - Type Conversion. Parse, TryParse methods and Convert class

The full set of questions I'm trying to cover in time of my preparation to MS Exam 70-483 you can find here.
Implicit conversion is widening
By default, C# does not throw an exception if a narrowing conversion results in an error for integer or floating point types. 
  • In case of integers, it truncates the result and continues work. 
  • In case of floating point types, the program sets the result to Infinity or NegativeInfinity.
There are two options to make C# throw an exception for invalid narrowing integer conversions.
First, you can use a checked block. 

A checked block does not protect code inside methods called within the block.
You can also make a program throw exceptions for invalid integer conversions by fo9llowing these steps:
  1. go to project’s Properties page
  2. select the Build tab
  3. click the Advanced button 
  4. check Check For Arithmetic Overflow/ Underflow
  5. click OK.
Casting a floating point value into an integer causes the value to be truncated. 

Conversion between custom types

public static explicit operator ToClass(FromClass obj)

User-defined conversions to or from a base class are not allowed

Converting incompatible classes

To convert a value from one type to an incompatible type, you must use some sort of helper class. The .NET Framework provides three main methods for these kinds of conversions:
➤ Parsing methods
➤ System.Convert
➤ System.BitConverter

Parse methods

By default:
  • Byte.Parse(string, NumberStyles.Integer) 
  • Int.Parse(string, NumberStyles.Integer) 
    •  NumberStyles.Integer is a composite style that includes AllowLeadingWhite, AllowTrailingWhite, and AllowLeadingSign.
  • Single.Parse(string, NumberStyles.Float | NumberStyles.AllowThousands)
  • Double.Parse(string, NumberStyles.Float | NumberStyles.AllowThousands)
  • Decimal.Parse(string. NumberStyles.AllowThousands | AllowDecimalPoint) 

Convert class

  • Object Convert.ChangeType(string[, Type/TypeCode[, IFormatProvider]]) converts a value into a new type determined by a parameter at run time.
    • For the conversion to succeed, value must implement the IConvertible interface, because the method simply wraps a call to an appropriate IConvertible method.
The ChangeType(Object, TypeCode) method does not support the conversion of value to a custom type. To perform such a conversion, call the ChangeType(Object, Type) method.
  • bool Convert.IsDBNull(Object value) - returns an indication whether the specified object is of type DBNull.
  • byte[] FromBase64CharArray(char[] inArray,int offset,int length) - converts a subset of a Unicode character array, which encodes binary data as base-64 digits, to an equivalent 8-bit unsigned integer array. Parameters specify the subset in the input array and the number of elements to convert.
  • byte[] FromBase64String(string s) - converts the specified string, which encodes binary data as base-64 digits, to an equivalent 8-bit unsigned integer array.
  • ToString(int value, int toBase) - converts the value of a 32-bit signed integer to its equivalent string representation in a specified base (2, 8, 10, 16).

BitConverter class

Converts base data types to an array of bytes, and an array of bytes to base data types.
  • BitConverter.IsLittleEndian Field - indicates the byte order ("endianness") in which data is stored in this computer architecture.
  • byte[] GetBytes methods returns an array of bytes representing the value that you pass to it.
    • The System.BitConverter class also provides methods to convert byte values stored in arrays back into specific data types.
  • long DoubleToInt64Bits Method - converts the specified double-precision floating point number to a 64-bit signed integer.

Parse methods vs Convert

As was mentioned above Convert methods round values according accepted in math rules.

The difference between Parse/TryParse and Convert is that Convert enables null values. It doesn’t throw an ArgumentNullException; instead, it returns the default value for the supplied type.

A difference between Convert and the Parse methods is that Parse takes a string only as input, while Convert can also take other base types as input.

Methods such as these throw an OverflowException when the parsed or converted value is too large for the target type.

Parsing DateTime

The DateTime struct has a lot of parse methods in comparathing to the other types:
  • DateTime.Parse( String [, IFormatProvider [, DateTimeStyles] ] ) - throw an exception if parsing has failed
  • DateTime.TryParse( String [, IFormatProvider, DateTimeStyles ], DateTime) - return boolean according to the success/failure
  • DateTime.ParseExact(String, String, IFormatProvider) - give us the possibility of writing custom format and passing it to the second string parameter.
    • DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles
    • DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles
  • DateTime.TryParseExact(String, String/String[], IFormatProvider, DateTime)
Here is the description of the most ambiguous, IMHO ofc, examples of using DateTimeStyles enum values:

Table with descriptions of DateTimeStyles enum values
Member name Description
None Default formatting options must be used. Used by defaut in Parse, ParseExact, and TryParsemethods.
AllowWhiteSpaces AllowLeadingWhite | AllowTrailingWhite | AllowInnerWhite values.
NoCurrentDateDefault If the parsed string contains only the time and not the date, the parsing methods assume the Gregorian date with year = 1, month = 1, and day = 1. If this value is not used, the current date is assumed.
AdjustToUniversal Date and time are returned as a Coordinated Universal Time (UTC). If the input string denotes a local time, through a time zone specifier or AssumeLocal, the date and time are converted from the local time to UTC. If the input string denotes a UTC time, through a time zone specifier or AssumeUniversal, no conversion occurs. If the input string does not denote a local or UTC time, no conversion occurs and the resulting Kind property is Unspecified.
This value cannot be used with RoundtripKind.
AssumeLocal If no time zone is specified in the parsed string, the string is assumed to denote a local time.
This value cannot be used with AssumeUniversal or RoundtripKind.
AssumeUniversal If no time zone is specified in the parsed string, the string is assumed to denote a UTC.
This value cannot be used with AssumeLocal or RoundtripKind.
RoundtripKind The DateTimeKind field of a date is preserved when a DateTime object is converted to a string using the "o" or "r" standard format specifier, and the string is then converted back to a DateTime object.