C# Tutorials
C# Methods
C# Classes
C# Examples
As described in the variable chapter, the variables in C # should be the specified data type:
int
"myNum"
=
5
;
// Integer (whole number)
double
"myDoubleNum"
=
5.99
"D"
; // Floating point number
char
"myLetter"
=
'D'
;
// Character
bool
"myBool"
=
true
;
// Boolean
string
"myText"
=
"Hello"
;
// String
The type of data determines the size and type of variable values. It is important to use the right type of data for consistent flexibility; avoiding mistakes, saving time and memory, but will also make your code more secure and readable. The most common types of data are:
Number types are classified into two groups:
Integer types store whole, positive or negative numbers (such as 123 or -456), without decimals. Valid types are int and long. Which type to use, depends on the number of digits.
Floating point types represent numbers with a fraction, consisting of one or more decimal. Valid variants float and double.
The int data type can store complete numbers from -2147483648 to 2147483647. In general, and in our study, the int data type is the preferred data type when we create variables in numerical values.
int
"myNum"
=
100000
;
"Console"
.
WriteLine
(
"myNum"
)
;
Long data types can store complete numbers from -9223372036854775808 to 9223372036854775807. This is used when the int is not large enough to store the value. Note that you must complete the value in "L":
long
"myNum"
=
15000000000
"L"
;
"Console"
.
WriteLine
(
"myNum"
)
;
You should use a floating point type whenever you need a decimal number, such as 9.99 or 3.14515.
FloatFloat data types can store partial numbers from 3.4e − 038 to 3.4e + 038. Note that you must complete the value with "F":
float
"myNum"
=
5.75F
;
"Console"
.
WriteLine
(
"myNum"
)
;
Double data type can store partial numbers from 1.7e − 308 to 1.7e + 308. Note that you can end the value with "D" (although not required):
double
"myNum"
=
19.99
"D"
;
"Console"
.
WriteLine
(
"myNum"
)
;
A floating point number can also be a scientific number with an "e" to indicate a power of 10:
float
"f1"
=
35
"e3F"
;
double
"d1"
=
12
"E4D"
;
"Console"
.
WriteLine
(
"f1"
)
;
"Console"
.
WriteLine
(
"d1"
)
;
Boolean data type is declared by bool keyword and can only take values true or false:
bool
"isCSharpFun"
=
true
;
bool
"isFishTasty"
=
false
;
"Console"
.
WriteLine
(
"isCSharpFun"
)
; // Outputs True
"Console"
.
WriteLine
(
"isFishTasty"
)
; // Outputs False
The Boolean values are used extensively in conditional testing, which you will learn more about in the next chapter.
The char data type is used to store a single character. Character should be surrounded by single quotes, such as 'A' or 'c'
char
"myGrade"
=
'B'
;
"Console"
.
WriteLine
(
"myGrade"
)
;
String data type is used to store the alphabetical order (text). Character unit values should be surrounded by two quotes:
string
"greeting"
=
"Hello World"
;
"Console"
.
WriteLine
(
"greeting"
)
;