Variables, Data Types, and Operators

The building blocks of every C# program

Posted by Rodrigo Castro on October 12, 2024

Variables store data your program uses. Each variable has a type that tells C# what kind of data it holds.

📦 Declaring Variables

1
2
3
4
5
int age = 25;                 // Integer
double price = 19.99;         // Decimal number
string name = "Alice";        // Text
bool isActive = true;         // True/False
char letter = 'A';            // Single character

🧮 Operators

Operators in C#

C# provides several types of operators to perform operations on variables:

Arithmetic Operators

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b

Assignment Operators

Operator Example Equivalent To
= a = 5  
+= a += 2 a = a + 2
-= a -= 2 a = a - 2
*= a *= 2 a = a * 2
/= a /= 2 a = a / 2
%= a %= 2 a = a % 2

Comparison Operators

Operator Description Example
== Equal to a == b
!= Not equal to a != b
< Less than a < b
> Greater than a > b
<= Less than or equal a <= b
>= Greater than or equal a >= b

Logical Operators

Operator Description Example
&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !a

Bitwise Operators

Operator Description Example
& Bitwise AND a & b
| Bitwise OR a | b
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
<< Left shift a << 2
>> Right shift a >> 2

Math Functions in C#

C# provides the System.Math class for common math operations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;

double x = -3.7;
Console.WriteLine(Math.Abs(x));      // Absolute value: 3.7
Console.WriteLine(Math.Ceiling(x));  // Ceiling: -3
Console.WriteLine(Math.Floor(x));    // Floor: -4
Console.WriteLine(Math.Round(x));    // Round: -4
Console.WriteLine(Math.Sqrt(16));    // Square root: 4
Console.WriteLine(Math.Pow(2, 3));   // 2 to the power 3: 8
Console.WriteLine(Math.Max(3, 7));   // Maximum: 7
Console.WriteLine(Math.Min(3, 7));   // Minimum: 3
Console.WriteLine(Math.Sign(x));     // Sign: -1
Console.WriteLine(Math.Truncate(x)); // Truncate: -3
Console.WriteLine(Math.Log(10));     // Natural log: 2.3025...
Console.WriteLine(Math.Log10(100));  // Base-10 log: 2
Console.WriteLine(Math.Exp(2));      // Exponential: e^2
Console.WriteLine(Math.Sin(Math.PI/2)); // Sine: 1
Console.WriteLine(Math.Cos(0));         // Cosine: 1
Console.WriteLine(Math.Tan(0));         // Tangent: 0

Note: To generate random numbers, use the Random class, not Math.
Example:

1
2
var rnd = new Random();
int randomNumber = rnd.Next(1, 101); // 1 to 100 inclusive

📝 Type Inference

You can let C# figure out the type:

1
2
var city = "London";  // C# knows this is a string
var number = 10;      // C# knows this is an int

⚠️ Good Practices

  • Use clear, descriptive names: userName, totalPrice
  • Pick the right type, don’t store numbers in a string!

💡 Try It!

Write a program that asks for a user’s name and age, then prints a greeting:

1
2
3
4
5
Console.Write("Enter your name: ");
string? name = Console.ReadLine();
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine() ?? "0");
Console.WriteLine($"Hi, {name}! You are {age} years old.");

Next: Learn about strong typing and type inference in C#.