Chapter 4: Using Types Flashcards
What happens during a narrowing conversion that fails for floats? (Double to float)
The result float is set to infinity. Check for this with float.IsInfinity (static method)
What type does the “checked” block work for and what does it do?
Only for integer. It throws an exception when a narrowing conversion fails.
Are implicit conversions allowed for narrowing conversions?
No
If x were an Int32, what would you get by calling:
BitConverter.GetBytes(x)
An array of bytes, 4 actually.
How is a cast handled from float to int?
Truncate
System.convert.toInt32 does what to a float-to-int conversion?
Rounds to nearest int.
Once you cast a reference type to an ancestor class, can you use it again later as the original type?
Yes. It never really changes, it’s a reference (address) after all. You can simply “convert” it back, and no values are lost.
Converting to an ancestor class is what kind of conversion? (Widening or narrowing?)
Widening. An explicit cast is required to go the other direction.
Will the following code throw?
Person person = new Person(); Employee employee = (Employee) person;
Yes, the underlying type is actually a Person not an employee.
The is operator will returns true for an object if…
The type being checked is in the class hierarchy of the type being tested.
What will an as operator return if the types are incompatible.
A null object.
What are the three main methods for converting values?
Parsing methods
System.Convert
System.BitCoverter
Parsing methods of conversion only apply to what kind of input and output?
Strings as input and primitive data types as output.
How can you get some parsing methods to accept non-numeric characters?
Give some examples
System.Globalization.NumberStyles
AllowLeadingSign
AllowLeadingParenthesis
AllowDecimalPoint
By default the decimal parser enables what NumberStyles?
Thousands and decimals (points)
In C# U.S. formats always apply to what regardless of the locale?
Literal values
What kind of rounding does ToIntXX, and ToUIntX use, and how does it work?
Banker’s rounding
Round to nearest integer, when tied go with nearest even.
How would you do a conversion where you won’t know the type until runtime?
Use Convert.ChangeType(value,type)
Once you have an array of bytes can you convert these into integers?
Yes, BitConverter has methods like ToInt
Define Boxing and Unboxing
Boxing is converting a value type into an object or an interface that is supported by the value’s type. Unboxing is the converting a boxed value back into its original value.
What are the two most common ways to engage interopperability?
COM Interop Platform Invoke (PInvoke)