Cast
You're all right...the cast is NOT necessary. However, it reflects a habit I got into when I was programming in C and earlier versions of C#. The random number generator used to return a value between 0 and 1.0 and was a double data type. Since a double requires 8 bytes and an int only uses 4 bytes, this would be an example of data narrowing (see page 67). Trying to assign an 8 byte thingie into a 4 byte thingie (i.e., data narrowing) runs the risk of losing information, you should always use a cast. It's like trying to pour 8 gallons of data into a 4 gallon bucket; some of the data is going to slop over the sides of the smaller bucket. That's why casts must always be used when data narrowing.
If you reverse the assignment direction; that is, assigning a 4 byte object into an 8 byte object, this is called data widening. Pouring 4 gallons of data into an 8 gallon bucket runs no risk of data lost and the use of a cast is not required. However, I always try to code so that I use a cast when data objects do not match. In other words, the cast is also a form of documentation that tells the reader of my code that I really intended to do this. In commercial code, I even do this with data widening. (There's no performance hit, since the compiler throws it away.)
The cast in this example is not necessary at all since the new random number generator defaults to returning an int data type. My mind was probably stuck with the old versions I used to use that always returned a double. Always keep in mind, however, that casts should always be used when assigning different data types, if for no other reason that it documents what you're doing. I think it's a good idea to always use casts whenever the data types don't match.
__________________
Jack Purdum, Ph.D.
Author: Beginning C# 3.0: Introduction to Object Oriented Programming (and 14 other programming texts)
|