Reputation: 1852
In Stellman & Greene (2010), one of the exercises is the following (edited for brevity):
Define the constants for the Hive: You need a constant for the amount of honey the hive starts with (3.2) and the maximum amount of honey the hive can store (15). (p. 555)
Alongside that paragraph, they place the following comment:
You'll have to figure out good names for each, as well as the types. For types, don't just think about initial values, but also the values these constants will be used with. Doubles pair best with other doubles, and ints with other ints. (p. 555, emphasis added)
Their solution to that exercise is the following (p. 556):
private const double InitialHoney = 3.2;
private const double MaximumHoney = 15;
They comment: "Since InitialHoney
will need to be a double, it's best to make this a double, too." (p. 556).
I searched the book, googled, and looked at StackOverflow, but could not find a reason why this is "best". Perhaps it saves explicit casting of one variable when both are used in a method, but explicitly defining integers as int
helps to prevent wrong use.
Question: So what am I missing? Why is it "best" to have matching variable types in C#?
Stellman, A. & Greene, J. (2010). Head First C#: A Brain-Friendly Guide (2nd edition). Sebastopol, CA: O’Reilly Media.
Upvotes: 0
Views: 21
Reputation: 64943
If a variable, field, constant is expected to be operable with other double
-typed ones and the result will be a double
, you should type all involved values with double
. And I would apply the same rule to any type.
Why forcing an implicit or explicit conversion from/to int
to/from double
if you know that you'll need to only get a double
result?
This wouldn't apply to a situation where a number might be used elsewhere. I'm not advocating for a rule that would say "if in a point in your code you need to use dobule
, all numbers will be typed with double
". Honestly, I would use common sense.
Upvotes: 1