Introduction to .NET Core
.NET Core is a free, cross-platform, open-source framework for building many types of applications, including web applications, mobile applications, desktop applications, and IoT applications.
Key features include:
- Cross-platform compatibility (Windows, macOS, Linux)
- High performance
- Modular architecture
- Open-source and community-driven
Core Fundamentals
Variables & Data Types
C# is statically typed, meaning you must declare the type of a variable.
int age = 30;
string name = "Alice";
double price = 19.99;
bool isAvailable = true;
DateTime today = DateTime.Now;
var message = "Implicitly typed"; // Type inferred as string
Operators
Common operators used in C#:
- Arithmetic:
+,-,*,/,% - Comparison:
==,!=,<,>,<=,>= - Logical:
&&(AND),||(OR),!(NOT) - Assignment:
=,+=,-=,*=,/= - Increment/Decrement:
++,--
int a = 10;
int b = 5;
int sum = a + b; // sum is 15
bool isEqual = (a == b); // isEqual is false
Control Flow (Conditional Statements)
if (temperature > 25) {
Console.WriteLine("It's hot!");
} else if (temperature > 15) {
Console.WriteLine("It's warm.");
} else {
Console.WriteLine("It's cool.");
}
switch (dayOfWeek) {
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("It's the weekend!");
break;
default:
Console.WriteLine("It's a weekday.");
break;
}
Loops
// For loop
for (int i = 0; i < 5; i++) {
Console.WriteLine(i);
}
// While loop
int counter = 0;
while (counter < 3) {
Console.WriteLine("Looping...");
counter++;
}
// ForEach loop (for collections)
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
Object-Oriented Programming (OOP)
Classes & Objects
Classes are blueprints for creating objects. Objects are instances of classes.
public class Car {
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public Car(string make, string model, int year) {
Make = make;
Model = model;
Year = year;
}
public void StartEngine() {
Console.WriteLine("Engine started!");
}
}
// Creating an object (instance)
Car myCar = new Car("Toyota", "Camry", 2022);
myCar.StartEngine();
Inheritance
Allows a class to inherit properties and methods from another class.
public class ElectricCar : Car {
public int BatteryCapacity { get; set; }
public ElectricCar(string make, string model, int year, int battery)
: base(make, model, year) {
BatteryCapacity = battery;
}
public void Charge() {
Console.WriteLine("Charging...");
}
}
Polymorphism
"Many forms." Allows methods to be called on objects of different types but behave differently.
public abstract class Shape {
public abstract double CalculateArea();
}
public class Circle : Shape {
public double Radius { get; set; }
public Circle(double radius) { Radius = radius; }
public override double CalculateArea() { return Math.PI * Radius * Radius; }
}
public class Rectangle : Shape {
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double width, double height) { Width = width; Height = height; }
public override double CalculateArea() { return Width * Height; }
}
Encapsulation
Bundling data (fields) and methods that operate on the data within a single unit (class) and restricting direct access to some of the object's components.
public class BankAccount {
private decimal _balance; // Private field
public decimal Balance {
get { return _balance; }
private set { _balance = value; } // Only accessible within the class
}
public void Deposit(decimal amount) {
if (amount > 0) {
Balance += amount;
Console.WriteLine($"Deposited: {amount:C}");
}
}
public bool Withdraw(decimal amount) {
if (amount > 0 && Balance >= amount) {
Balance -= amount;
Console.WriteLine($"Withdrew: {amount:C}");
return true;
}
return false;
}
}
Collections
Used to store and manage groups of objects.
- Array (
[]): Fixed size. - List (
List<T>): Dynamically sized, similar to an array. - Dictionary (
Dictionary<TKey, TValue>): Key-value pairs. - HashSet (
HashSet<T>): Unique elements.
// List
List<string> names = new List<string> { "Bob", "Charlie" };
names.Add("David");
// Dictionary
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Bob"] = 25;
ages["Charlie"] = 30;
int bobsAge = ages["Bob"]; // bobsAge is 25
Asynchronous Programming
Allows your application to remain responsive by performing long-running operations on a background thread. Use async and await keywords.
public async Task<string> DownloadDataAsync(string url) {
using (var httpClient = new HttpClient()) {
string data = await httpClient.GetStringAsync(url);
return data;
}
}
// Calling the async method
async void GetData() {
string result = await DownloadDataAsync("http://example.com");
Console.WriteLine(result.Substring(0, 50));
}
Error Handling (Exceptions)
Use try-catch-finally blocks to handle potential errors.
try {
// Code that might throw an exception
int result = 10 / 0;
} catch (DivideByZeroException ex) {
Console.WriteLine("Error: Cannot divide by zero.");
Console.WriteLine(ex.Message);
} catch (Exception ex) {
Console.WriteLine("An unexpected error occurred.");
Console.WriteLine(ex.ToString());
} finally {
Console.WriteLine("This block always executes.");
}
LINQ (Language Integrated Query)
Provides a powerful and flexible way to query data from various sources.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Query syntax
var evenNumbersQuery = from num in numbers
where num % 2 == 0
select num;
// Method syntax
var evenNumbersMethod = numbers.Where(num => num % 2 == 0);
// To execute the query and get results
foreach (int evenNum in evenNumbersQuery) {
Console.WriteLine(evenNum);
}