Store and Retrieve Data Using Literal and Variable Values in C#
C# is a strongly typed language where each variable has a defined type which can be assigned to different values.
Question
Which of the following lines of code creates a variable correctly?
Complete this challenge on freeCodeCamp.
Option 1
int x = 12.3m;
Here we are declaring a variable called x
with a type of int
. The key point to remember is that integers are whole numbers.
Next we assign x
to the literal value 12.3m
. The decimal point signifies that this is a floating-point numeric type which can have decimal places. The m
suffix is the literal for a decimal
value.
C# is a strongly typed language and makes sure that all operations in your code are type safe. When you declare a variable you can’t assign a value not compatible with its declared type. For example, you can’t declare an int
and assign it a decimal
value as this would cause data loss which could result in unexpected bugs.
If you tried to compile the code in this example, you would get a compiler error.
This is incorrect.
Option 2
decimal x = 12.3m;
Here we are declaring a variable called x
with a type of decimal
.
Next we assign x
to the literal value 12.3m
. The m
suffix is the literal for a decimal
value.
This is correct.
Option 3
bool x = 'False';
Here we are declaring a variable called x
with a type of bool.
A bool can be assigned the literal value true
and false
.
Next we assign x
to the value 'False'
.
The single quote characters here indicate this is a char type.
A char can be assigned to a single character.
If you tried to compile the code in this example, you would get a compiler error.
This is incorrect.