0
float x = 19.2F;

I understand that without F the variable is assumed to be a double by default. But isn't that a bit redundant since we're declaring the variable to be a float in the first place?

Can someone explain why this is the case?

default
  • 11,485
  • 9
  • 66
  • 102
Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
  • Please take out the attitude in your questions. Title should read "Why is 'f' required on floats in C#" not "Redundancy in variable creation" – Jason Feb 21 '14 at 12:23

2 Answers2

4

It can be somehow seen as being redundant. But it is for your safety. Simply speaking, there is no implicit conversion between float and double, because you can lose information (accuracy). And this CAN be made by mistake so it is the language designers decision to make you explicitly specify that you are aware of that conversion.

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
1

Konrad is right.

If you see this as "duplicity", you can use eg. var:

var myFloat = 23f;

Tada, the "duplicit" float is gone :))

Luaan
  • 62,244
  • 7
  • 97
  • 116
  • Sadly that doesn't seem to work in Unity3d. **error** CS0825: The contextual keyword `var' may only appear within a local variable declaration – Ghoul Fool Feb 21 '14 at 15:32
  • @GhoulFool Unity actually uses it's own C# compiler (and many more things) based on Mono. However, it lags not just behind MS C# (and .NET), but behind Mono as well. `var` was added in C# 3.0, while Unity is stuck in the C# 2.0 world (and has been for some time), so you're out of luck, sorry. I had to ditch Unity because I really wanted C# 4.0, but you'll just have to stick with explicitly saying `float myFloat = 23f;`. – Luaan Feb 21 '14 at 15:43