I wrote a code snippet that day, and Visual Studio throws an error message regarding type conversation between
This is the original code:
float number = 1.35; //Compiler throw an error
As you can see, I declared a variable named number, and its data type is
Float. The number’s value is 1.35. However, Visual Studio throws the error as:
Literal of type double cannot be implicit converted to type ‘float’; use an ‘F’ suffix to create a literal of this type
Why does it happen?
Double and Float
The documentation in Microsoft explains why. Have a look the chart blow.
The double type has a larger range than Float type in C#; its size is larger than Float type in memory. The compiler chooses the data type which has a larger size in memory by default.
Let’s go back to our code. The compiler thinks 1.35 is a
Double type by default, which prevents from trigger a memory leak. To use the
Float data type, we need to add a suffix
f in our code. The new code should be:
float number = 1.35f; //Compiler know this is a float type precisely.