I'm studying for the 70-483 exam and I have doubts about converting types. I follow a book, at the end of each chapter there are some questions/answer, and with one i'm completly confuse.
If the Manager class inherits from the Employee class, and the Employee and Customer classes both inherit from the Person class, then which of the following are narrowing conversions?
a. Converting a Person to a Manager
b. Converting an Employee to a Manager
c. Converting an Employee to a Person
d. Converting a Manager to a Person
e. Converting a Manager to an Employee
f. Converting a Person to an Employee
g. Converting a Customer to an Employee
h. Converting an Employee to a Customer
the answers are :
"A, B, F . (In a sense you could technically consider g and h to be considered narrowing conversions, but actually they are just invalid conversions.)"
From what i understand, i thought a,b,f to be widening conversions
A widening conversion is a conversion where every value of the original type can be represented in the result type.
A narrowing conversion is a conversion where some values of the
original type cannot be represented in the result type.
If I do
Person originalType = new Customer();
Employee resultType = (Employee)originalType; //this line is Example f in the book.
The 2nd line would fail with a invalid cast exception. That means there is a value that Person
can be that will fail when you convert to Employee
.
If you look at your two rules again (emphasis mine)
- A widening conversion is a conversion where every value of the original type can be represented in the result type.
- A narrowing conversion is a conversion where some values of the original type cannot be represented in the result type.
You will see this will fall under the 2nd rule because we did find a value of the original type that could not be represented as the result type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With