C# Variables and Data Types

Store values in variables, choose the right built-in type (int, long, double, decimal, bool, char, string), use var for type inference, declare constants, and convert between types.

Lesson 2 of 43Beginner17 min read

Programs work with data: a user's name, the number of items in a basket, a price, whether someone is logged in. A variable is a named place to store a value so you can use and change it later.

C# is statically typed, so every variable has a type that decides what kind of value it can hold and what you can do with it. You can't accidentally put text into a variable meant for a number: the compiler stops you. That might feel strict at first, but it catches a whole category of bugs before your program ever runs, and it lets your editor offer accurate suggestions as you type.

In this lesson you'll declare variables, meet the built-in types you'll use every day, let the compiler infer types with var, make values that never change with const, and convert safely between types, including turning text typed by a user into a number.

Declaring variables

C#
int age = 30;              // type, name, value
string name = "Ada";
age = 31;                  // change the value later

int count;                 // declare now...
count = 5;                 // ...assign before use
  • A local variable must be assigned before it's read, or the compiler reports error CS0165.
  • Names start with a letter or underscore, contain letters, digits and underscores, and use camelCase: totalPrice, isLoggedIn.
  • Choose descriptive names; basketTotal tells a reader far more than bt.

Built-in types

TypeHoldsExample
intWhole numbers up to about 2.1 billionint stock = 120;
longVery large whole numberslong views = 9_000_000_000;
doubleDecimal numbers (fast, approximate)double distance = 12.5;
floatSmaller, less precise decimals, used in Unityfloat speed = 3.5f;
decimalExact decimals for moneydecimal price = 19.99m;
booltrue or falsebool inStock = true;
charOne character, in single quoteschar grade = 'A';
stringText, in double quotesstring city = "Leeds";

Suffixes tell C# the literal's type: f for float, m for decimal, L for long. Underscores in numbers like 1_000_000 are just for readability.

var, const and conversions

var lets the compiler work out the type from the value: var total = 0; is an int. The type is still fixed; var only saves typing.

const declares a value that can never change: const int MaxItems = 10;.

Converting between types:

  • Implicit conversions happen automatically when nothing can be lost: int to long or double.
  • Explicit casts are needed when data could be lost: (int)9.8 gives 9, cutting off the fraction.
  • Parsing turns text into numbers: int.Parse("42"), or the safer int.TryParse(text, out int n), which returns false instead of crashing when the text isn't a number.

Type ranges, literals and default values

Every numeric type has a fixed size, so it has a smallest and largest value. You can ask for them with MinValue and MaxValue:

C#
Console.WriteLine(int.MaxValue);    // 2147483647
Console.WriteLine(int.MinValue);    // -2147483648
Console.WriteLine(long.MaxValue);   // 9223372036854775807

Whole numbers can also be written in hexadecimal with 0x or binary with 0b. 0xFF is 255 and 0b1010 is 10, which is handy for colours and bit flags.

Each type also has a default value: 0 for numbers, false for bool and null for string. You get it with the default keyword, so default(int) is 0. Fields in a class start at their default value automatically, but local variables don't, which is why the compiler insists you assign them before use.

The short type names are aliases for .NET types: int is System.Int32, long is System.Int64, double is System.Double and string is System.String. You'll see both forms in documentation, and they mean exactly the same thing.

C# Basics Syntax

Variables and types

int count = 3;
double ratio = 0.75;
decimal price = 9.99m;
float speed = 2.5f;
bool done = false;
char letter = 'x';
string text = "hello";
var inferred = 42;            // int
const double Pi = 3.14159;
int whole = (int)7.9;         // 7
int parsed = int.Parse("12");
bool ok = int.TryParse("abc", out int n);   // false, n is 0

C# Basics Summary

  • Variables have a type, a name and a value; locals must be assigned before use.
  • int, long, double, float, decimal, bool, char and string are the everyday types.
  • var infers the type from the value; the type is still fixed.
  • const declares a value that never changes.
  • Casts convert explicitly; int.TryParse converts text safely.

C# Basics Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A product record in variables

C#
string product = "Desk lamp";
decimal price = 24.99m;
int stock = 12;
bool onSale = false;
char sizeCode = 'M';

Console.WriteLine(product);
Console.WriteLine(price);
Console.WriteLine(stock);
Console.WriteLine(onSale);
Console.WriteLine(sizeCode);

stock = stock - 3;
Console.WriteLine("Stock after sales: " + stock);
Output
Desk lamp
24.99
12
False
M
Stock after sales: 9
Line-by-line explanation
  1. Line 2The m suffix makes 24.99 a decimal, the right type for money.
  2. Line 10C# prints booleans as True and False, with capital letters.
  3. Line 13A variable can be given a new value of the same type.
  4. Line 14+ joins a string and a number into one string.
Example 2

var, const and casting

C#
var quantity = 3;
var unitPrice = 2.5;
const int MaxPerOrder = 5;

double total = quantity * unitPrice;
Console.WriteLine(total);

int rounded = (int)total;
Console.WriteLine(rounded);

long big = quantity;
Console.WriteLine(big + MaxPerOrder);

Console.WriteLine(quantity.GetType().Name);
Console.WriteLine(unitPrice.GetType().Name);
Output
7.5
7
8
Int32
Double
Line-by-line explanation
  1. Lines 1 to 2var infers int from 3 and double from 2.5.
  2. Line 3A const value is fixed when the program is compiled.
  3. Line 8The cast cuts off the fraction; it doesn't round.
  4. Line 11int converts to long automatically, because nothing can be lost.
  5. Lines 14 to 15GetType shows the real .NET type names behind int and double.
Example 3

Parsing text safely

C#
string[] inputs = { "42", "seven", "  15 ", "" };

foreach (string text in inputs)
{
    if (int.TryParse(text, out int number))
    {
        Console.WriteLine($"Got {number}, doubled is {number * 2}");
    }
    else
    {
        Console.WriteLine($"'{text}' is not a whole number");
    }
}

Console.WriteLine(0.1 + 0.2 == 0.3);
Console.WriteLine(0.1m + 0.2m == 0.3m);
Output
Got 42, doubled is 84
'seven' is not a whole number
Got 15, doubled is 30
'' is not a whole number
False
True
Line-by-line explanation
  1. Line 5TryParse returns true or false and puts the number in the out variable when it works.
  2. Line 7$"..." is an interpolated string; values in braces are inserted.
  3. Line 5Leading and trailing spaces are allowed, so " 15 " parses.
  4. Line 15double arithmetic is approximate, so the comparison is False.
  5. Line 16decimal arithmetic is exact, so it's True.

Common C# Basics Mistakes

Assigning the wrong type

Don't
int age = "30";              // error CS0029: cannot convert string to int
Do
int age = int.Parse("30");

Forgetting the m suffix on decimals

Don't
decimal price = 9.99;        // error CS0664: use the 'M' suffix
Do
decimal price = 9.99m;

int.Parse on user input

Don't
int qty = int.Parse(Console.ReadLine());     // crashes on "two" or an empty line
Do
if (!int.TryParse(Console.ReadLine(), out int qty))
{
    qty = 1;
}

C# Basics in Real Projects

Types in business code

Shopping carts, invoices and banking systems store amounts as decimal so totals are accurate to the penny. Counts and ids use int or long, flags use bool, and anything users type arrives as a string that's parsed with TryParse. Game code in Unity uses float for positions and speeds, because graphics hardware works with floats.

C# Basics FAQ

When should I use var in C#?

Use var when the type is obvious from the right-hand side, such as var names = new List<string>();, because repeating the type adds nothing. Write the type out when it isn't obvious, for example int count = GetCount();. Either way the variable gets a fixed type at compile time, so var never makes C# dynamic.

What is the difference between double and decimal?

double stores numbers in binary floating point, so it's fast and covers a huge range but can't represent values like 0.1 exactly. decimal stores numbers in base 10 with up to 28 or 29 significant digits, so money adds up exactly. Use decimal (with the m suffix) for prices and double for measurements.

What is the difference between string and String in C#?

There's no difference: string is the C# keyword alias for the System.String class. The same goes for int and System.Int32. Most style guides use the lowercase keywords for declarations, such as string name.

How do I convert a string to an int in C#?

Use int.TryParse(text, out int number) when the text might not be valid, for example when a user typed it. It returns false instead of throwing an exception. Use int.Parse(text) only when you're sure the text is a valid number, because it throws a FormatException otherwise.

What happens if I go past int.MaxValue?

By default the value wraps around silently, so int.MaxValue + 1 at run time becomes -2147483648. Wrap the calculation in checked(...) to get an OverflowException instead, or use long when your numbers can grow beyond about 2.1 billion.

C# Basics Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the declaration to store a price exactly.

 price = 4.50m;
Predict the outputeasy

What does this print?

int x = (int)8.9;
Console.WriteLine(x);
Multiple choicemedium

What type does var n = 5.0; give n?

Predict the outputmedium

What does this print?

bool ok = int.TryParse("12a", out int n);
Console.WriteLine($"{ok} {n}");
Multiple choicehard

Why does double total = 0.1 + 0.2; not equal 0.3 exactly?

C# Basics Quiz

5 questions to check what you learned.

  1. Which type holds true or false?

    • bool
    • int
    • string
    • char
  2. What does const mean?

    • The variable is private
    • The value is fixed and can never change
    • The variable can hold any type
    • The value is calculated later
  3. Which literal is a char?

    • "A"
    • A
    • 'A'
    • A
  4. Does var make a variable dynamically typed?

    • Yes, it can hold any type later
    • Only for strings
    • No, the compiler infers one fixed type from the value
    • Only inside methods
  5. Which method converts text to an int without throwing on invalid input?

    • int.Parse
    • Convert.ToInt32
    • (int)text
    • int.TryParse