C Sharp int: Difference between revisions
From Coderwiki
More actions
new: info, example |
add: casting |
||
| (One intermediate revision by the same user not shown) | |||
| Line 2: | Line 2: | ||
See [[Integer]] for generic information about what integers can represent and how they are represented in [[memory]]. | See [[Integer]] for generic information about what integers can represent and how they are represented in [[memory]]. | ||
== Size == | |||
A '''long''' in C# is represented by '''4''' [[Byte|bytes]], or '''32''' [[Bit|bits]]. | |||
This means it can store integral values from <code>-2,147,483,648</code> to <code>2,147,483,647</code>. | |||
For [[Integer|integers]] that don't fit this range, you can use the [[C Sharp long]] data type instead. | |||
== Example == | == Example == | ||
| Line 9: | Line 16: | ||
int c = (int)15.2; // 15 | int c = (int)15.2; // 15 | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== Casting == | |||
To [[Casting|cast]] to an '''int''', you can use the [[C Sharp casting|casting operator]] <code>(int)</code> or the [[C Sharp Convert.ToInt32|Convert.ToInt32]] [[function]]:<syntaxhighlight lang="cs" line="1"> | |||
char a = 'A'; | |||
int b = (int)a; // 65 | |||
int c = Convert.ToChar(a); // 65 | |||
</syntaxhighlight>This is different to casting to a [[C Sharp long|long]], which uses the <code>(long)</code> operator or the [[C Sharp Convert.ToInt64|Convert.ToInt64]] function. | |||
Latest revision as of 13:10, 19 August 2025
The int class in C Sharp is a data type which can store positive and negative whole numbers in variables.
See Integer for generic information about what integers can represent and how they are represented in memory.
Size
edit edit sourceA long in C# is represented by 4 bytes, or 32 bits.
This means it can store integral values from -2,147,483,648 to 2,147,483,647.
For integers that don't fit this range, you can use the C Sharp long data type instead.
Example
edit edit sourceint a;
int b = 74;
int c = (int)15.2; // 15
Casting
edit edit source
To cast to an int, you can use the casting operator (int) or the Convert.ToInt32 function:
char a = 'A';
int b = (int)a; // 65
int c = Convert.ToChar(a); // 65
This is different to casting to a long, which uses the (long) operator or the Convert.ToInt64 function.