C# Data Types
A data type is the kind of value a variable can hold in C#. Each type stores its values in its own way.
Whole and decimal types
The int and long variables hold whole numbers. The double variable holds a decimal number.
using System;
class Program
{
static void Main(string[] args)
{
int count = 50000;
long big = 9000000000L;
double rate = 19.99;
Console.WriteLine(count);
Console.WriteLine(big);
Console.WriteLine(rate);
}
}Float and decimal
A float value ends with the letter f. A decimal value ends with the letter m.
using System;
class Program
{
static void Main(string[] args)
{
float price = 5.5f;
decimal total = 19.99m;
Console.WriteLine(price);
Console.WriteLine(total);
}
}A float needs f
A decimal value is a double by default. A float variable refuses it without the letter f.
using System;
class Program
{
static void Main(string[] args)
{
float score = 5.5;
Console.WriteLine(score);
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
int items = 24;
long boxes = 3000000L;
double price = 12.5;
decimal total = 300.0m;
Console.WriteLine(items);
Console.WriteLine(boxes);
Console.WriteLine(price);
Console.WriteLine(total);
}
}Key points
- int and long hold whole numbers.
- long holds whole numbers too large for int.
- float, double, and decimal hold decimal numbers.
- A float value carries the letter f after its number.
- A decimal value carries the letter m after its number.
- bool holds true or false.
- char holds one character in single quotes.
- string holds text in double quotes.
In this example, the first line prints the int count 24. The second line prints the long count 3000000. The third line prints the double price 12.5. The fourth line prints the decimal total 300.0.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
| Type | Stores | Example |
|---|---|---|
| int | Whole numbers | 42 |
| long | Large whole numbers | 9000000000L |
| float | Decimal numbers with less precision | 5.5f |
| double | Decimal numbers with more precision | 19.99 |
| decimal | Exact decimal numbers for money | 19.99m |
| bool | True or false values | true |
| char | One character | 'A' |
| string | Text with many characters | "Hello" |
| byte | Small whole numbers from 0 to 255 | 200 |
| sbyte | Small whole numbers with a sign | -50 |
| short | Whole numbers in a smaller range | 3000 |
| ushort | Positive whole numbers in a smaller range | 60000 |
Exercise
Which letter must follow a decimal value stored in a float variable?