Kerdan
Kerdan

Reputation: 133

c# - Narrowing and widening on class inheritance

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

Upvotes: 5

Views: 4494

Answers (3)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

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.

Upvotes: 4

Rok Povsic
Rok Povsic

Reputation: 4915

Converting a Person to a Manager is not widening, since not all Person objects (the original type) can be represented in the result type. Why? Because Customer is also a Person and Customer can not be Manager.

But if we were to convert from Manager to Person, that we can do for every Manager object. There is no Manager we can not convert to a Person. Hence this is widening.

Makes sense?

Upvotes: 3

Remy Grandin
Remy Grandin

Reputation: 1686

Narrowing is when you create a class for a subset of a bigger group, to store additional data mostly.

So when you convert a person to an employee, you are looking at it from the perspective of a smaller/narrower group/type (an employee is a person but a person is not necessarly an employee).

The same apply for converting an Employee to a Manager and converting a Person to an Employee

Upvotes: 1

Related Questions