C# Basics
Welcome to the fundamental concepts of C# programming. This tutorial covers the essential building blocks you need to start writing C# code.
Variables and Data Types
Variables are containers for storing data values. C# is a statically typed language, which means you must declare the type of a variable before you can use it.
Common data types include:
int: For whole numbers (e.g., 10, -5).double: For floating-point numbers (e.g., 3.14, -0.5).char: For single characters (e.g., 'A', '$').string: For sequences of characters (e.g., "Hello, World!").bool: For boolean values (trueorfalse).
Declaring and Initializing Variables
int age = 30;
string name = "Alice";
double price = 99.99;
bool isActive = true;
Console.WriteLine($"Name: {name}, Age: {age}, Price: {price}, Active: {isActive}");
Operators
Operators are symbols that perform operations on variables and values.
- Arithmetic Operators:
+,-,*,/,%(modulo) - Assignment Operators:
=,+=,-=, etc. - Comparison Operators:
==,!=,>,<,>=,<= - Logical Operators:
&&(AND),||(OR),!(NOT)
Using Operators
int a = 10;
int b = 5;
int sum = a + b; // sum will be 15
int difference = a - b; // difference will be 5
bool isEqual = (a == b); // isEqual will be false
bool isGreater = (a > b); // isGreater will be true
Control Flow Statements
Control flow statements allow you to execute different code blocks based on certain conditions or to repeat code.
Conditional Statements (if, else if, else)
These statements execute code blocks only if a specified condition evaluates to true.
Conditional Example
int score = 85;
if (score >= 90) {
Console.WriteLine("Grade: A");
} else if (score >= 80) {
Console.WriteLine("Grade: B");
} else if (score >= 70) {
Console.WriteLine("Grade: C");
} else {
Console.WriteLine("Grade: D");
}
Loops (for, while, foreach)
Loops are used to execute a block of code repeatedly.
Loop Examples
// For loop
for (int i = 0; i < 5; i++) {
Console.WriteLine($"For loop iteration: {i}");
}
// While loop
int count = 0;
while (count < 3) {
Console.WriteLine($"While loop iteration: {count}");
count++;
}
// Foreach loop (often used with collections)
string[] colors = {"Red", "Green", "Blue"};
foreach (string color in colors) {
Console.WriteLine($"Color: {color}");
}
Methods
Methods (also known as functions) are blocks of code that perform a specific task. They help in organizing code and making it reusable.
Method Definition and Call
// Define a method
public static void Greet(string personName) {
Console.WriteLine($"Hello, {personName}!");
}
// Call the method
Greet("Bob"); // Output: Hello, Bob!
public static int AddNumbers(int num1, int num2) {
return num1 + num2;
}
int result = AddNumbers(5, 3); // result will be 8
Console.WriteLine($"Sum: {result}");