Class diagram for the code below: HoneyManufacturer class and NectarCollector class both extend Bee class. Bee class implements interface IWorker.
IWorker[] bees = new IWorker[8];
bees[0] = new HoneyManufacturer();
bees[1] = new NectarCollector();
bees[2] = bees[0] as IWorker; // bees[2] is of type HoneyManufacturer, why?
bees[3] = bees[1] as NectarCollector;
bees[4] = IWorker;
bees[5] = bees[0];
bees[6] = bees[0] as Object;
bees[7] = new IWorker();
So I understand that the bees[4] and bees[7] lines won't compile because interfaces cannot be instantiated. I still have the following questions:
For the bees[2] line, my understanding is that the "as" keyword converts bees[0] to IWorker type since HoneyManufacturer class extends Bee class which implements IWorker interface. But bees[2] is still of type HoneyManufacturer (I've checked in my program), why?
For the bees[6] line, book says it will compile but it doesn't compile in my Visual Studio 2022. Why?
I've already read so many other posts about casting and type conversion but I cannot find the answer to my specific question.
Thank you so much for your help!
Edit 1: (since I couldn't reply too long as a comment)
Thank you so much for your answers, really really appreciate it!!!
So do you mean that bees[2] = bees[0] as IWorker
is only casting the reference variable, but not the object?
I checked the type of bees[2] with this code afterwards and it returns TRUE for all three.
Console.WriteLine(bees[2] is Bee);
Console.WriteLine(bees[2] is HoneyManufacturer);
Console.WriteLine(bees[2] is IWorker);
I thought that bees[2] would've been converted to IWorker and thus no longer of type HoneyManufacturer. Is there any circumstance when we actually need to do something like bees[2] = bees[0] as IWorker
?
The book I'm reading is Head First C# and this is an exercise on page 381. It asks me to pick out the lines that won't compile and gives the answer of the bees[4] line and the bees[7] line. Then it asks which values of i
would make this evaluate to TRUE:
(bees[i] is Bee)
The answer given is 0, 1, 2, 3, 5, 6 and I didn't understand why bees[2] is Bee.
Edit 2: (since I couldn't reply too long as a comment)
So is it correct to understand it in the following way?
What bees[2] = bees[0] as IWorker
is doing is that it takes the reference variable bees[0]
(which points to an object of HoneyManufacturer
type) and casts it to a reference variable of IWorker
type, and then assigns it to bees[2]
. So bees[2]
is now a reference variable of IWorker
type, but it still points to the same object that bees[0]
points to, which is of HoneyManufacturer
type. And this line is essentially redundant because bees[2]
is a reference variable of IWorker
type to begin with, due to the first line IWorker[] bees = new IWorker[8];
where an array of reference variables of IWorker
type is created and given the name bees
.