C# Essentials Tutorial
Welcome to the C# Essentials tutorial. This guide covers the fundamental concepts of the C# programming language, designed for beginners looking to build a strong foundation.
Introduction to C#
C# (pronounced "C sharp") is a modern, object-oriented programming language developed by Microsoft. It runs on the .NET framework and is widely used for developing a variety of applications, including desktop applications, web services, and games.
Key features of C# include:
- Type-safe: Helps prevent common programming errors.
- Object-oriented: Based on concepts like encapsulation, inheritance, and polymorphism.
- Component-oriented: Encourages modular development.
- Versatile: Can be used for a broad range of application types.
To start coding in C#, you'll typically need a development environment like Visual Studio or Visual Studio Code, along with the .NET SDK.
Variables and Data Types
Variables are used to store data. In C#, you must declare a variable's type before you can use it. Common built-in data types include:
int: For whole numbers (e.g., 10, -5).double: For floating-point numbers (e.g., 3.14, -0.5).bool: For boolean values (trueorfalse).string: For sequences of characters (e.g., "Hello, World!").char: For single characters (e.g., 'A', '7').
Example:
int age = 30;
string name = "Alice";
double pi = 3.14159;
bool isStudent = false;
You can also use the var keyword for implicit typing, where the compiler infers the type from the assigned value.
var message = "Learning C#"; // message is inferred as string
var count = 100; // count is inferred as int
Operators
Operators perform operations on variables and values. C# supports various operators:
Arithmetic Operators
+(Addition)-(Subtraction)*(Multiplication)/(Division)%(Modulo - returns the remainder)
Comparison Operators
==(Equal to)!=(Not equal to)>(Greater than)<(Less than)>=(Greater than or equal to)<=(Less than or equal to)
Logical Operators
&&(Logical AND)||(Logical OR)!(Logical NOT)
Example:
int a = 10;
int b = 5;
int sum = a + b; // sum is 15
bool isEqual = (a == b); // isEqual is false
Control Flow (if, else, loops)
Control flow statements allow you to execute code conditionally or repeatedly.
if, else if, else
Used to execute blocks of code based on conditions.
int temperature = 25;
if (temperature > 30) {
Console.WriteLine("It's hot!");
} else if (temperature > 20) {
Console.WriteLine("It's warm.");
} else {
Console.WriteLine("It's cool.");
}
Loops (for, while, foreach)
Used to repeat a block of code multiple times.
for loop
for (int i = 0; i < 5; i++) {
Console.WriteLine("Iteration: " + i);
}
while loop
int count = 0;
while (count < 3) {
Console.WriteLine("While loop: " + count);
count++;
}
foreach loop
Used to iterate over collections.
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
Methods
Methods (also known as functions or subroutines) are blocks of code that perform a specific task. They help organize code and make it reusable.
Syntax:
[access_modifier] [return_type] MethodName([parameters]) {
// Method body
return some_value; // if return_type is not void
}
Example:
public static int Add(int num1, int num2) {
return num1 + num2;
}
public static void Greet(string name) {
Console.WriteLine("Hello, " + name + "!");
}
// Calling methods:
int result = Add(5, 3); // result is 8
Greet("Bob"); // Prints "Hello, Bob!"
Classes and Objects
C# is an object-oriented language. A class is a blueprint for creating objects. An object is an instance of a class.
A class typically contains fields (data members) and methods (member functions).
Example:
public class Car {
// Fields
public string Model;
public int Year;
// Constructor
public Car(string model, int year) {
Model = model;
Year = year;
}
// Method
public void DisplayInfo() {
Console.WriteLine($"Car: {Year} {Model}");
}
}
// Creating and using an object:
Car myCar = new Car("Toyota Camry", 2022);
myCar.DisplayInfo(); // Output: Car: 2022 Toyota Camry
Collections
Collections are used to store groups of objects. The System.Collections.Generic namespace provides powerful generic collection types.
List<T>
A dynamic array that can grow or shrink.
using System.Collections.Generic;
var numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
Console.WriteLine(numbers[0]); // Output: 1
foreach (int num in numbers) {
Console.WriteLine(num);
}
Dictionary<TKey, TValue>
A collection of key-value pairs.
using System.Collections.Generic;
var capitals = new Dictionary<string, string>();
capitals["USA"] = "Washington D.C.";
capitals["UK"] = "London";
Console.WriteLine(capitals["USA"]); // Output: Washington D.C.
Error Handling (Exceptions)
Exceptions are events that occur during execution that disrupt the normal flow of the program's instructions. C# uses the try-catch block for exception handling.
try {
// Code that might throw an exception
int[] numbers = { 1, 2 };
Console.WriteLine(numbers[5]); // This will throw an IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex) {
Console.WriteLine("Error: Index is out of bounds.");
Console.WriteLine(ex.Message);
}
catch (Exception ex) {
// Catches any other type of exception
Console.WriteLine("An unexpected error occurred.");
}
finally {
// Code that will always execute, regardless of exceptions
Console.WriteLine("Cleanup operations.");
}
The throw keyword can be used to manually raise an exception.