Easy c# code explanation

Hey guys, trying to understand boxing/unboxing, and I have a small code snippit I dont quite understand.

FileStream fs = new FileStream(“data.bin”, FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);

for (int i = 0;i , 11; i++)



My question is:

  1. this code - (int)i - is casting i as an interger, right?

  2. why is it casting i as an integer when seems to me to already be an integer?

An example of casting that make sense to me is:

object o = 123;

int i = (int)o;

Thanks for any explanations

  1. Yes. It is explicitly casting an int to an int.
  2. You’d have to ask the person who wrote that code. I can’t see any reason for it.

Your example makes sense. The first line boxes the value 123, and the second line unboxes it.


To find out why - test the output of that first snippet with the cast and then without the cast. If the output is the same then the you can conclude that the cast is pointless.

the code is sample code in the MTCS 70-536 .NET framework foundation exam book.

i will try to run it both ways and see if there is a difference

There will not (and cannot) be any difference.


ok, thanks D - that saves me some time testing