Core .NET Concepts
This section covers the fundamental building blocks of the .NET ecosystem. Understanding these concepts is crucial for developing robust and efficient applications.
Types and Variables
.NET is a type-safe environment. Every piece of data is of a specific type. Types define the structure and behavior of data.
- Value Types: Stored directly on the stack (e.g.,
int
,float
,bool
,struct
). - Reference Types: Stored on the heap, with a reference on the stack (e.g.,
string
,class
,array
,delegate
).
Variables are named containers for storing data of a particular type.
int count = 10;
string message = "Hello, .NET!";
Operators
Operators perform operations on operands (variables and values). Common operators include:
- Arithmetic:
+
,-
,*
,/
,%
- Comparison:
==
,!=
,<
,>
,<=
,>=
- Logical:
&&
(AND),||
(OR),!
(NOT) - Assignment:
=
,+=
,-=
, etc.
Control Flow
Control flow statements determine the order in which code is executed.
- Conditional Statements:
if
,else if
,else
,switch
- Looping Statements:
for
,foreach
,while
,do-while
if (count > 5) {
Console.WriteLine("Count is greater than 5.");
} else {
Console.WriteLine("Count is 5 or less.");
}
for (int i = 0; i < 3; i++) {
Console.WriteLine($"Iteration {i}");
}
Methods
Methods (also known as functions or procedures) are blocks of reusable code that perform a specific task. They can accept parameters and return values.
public int Add(int a, int b) {
return a + b;
}
int sum = Add(5, 3); // sum will be 8
Classes and Objects
Object-Oriented Programming (OOP) is a core paradigm in .NET. A class is a blueprint for creating objects, while an object is an instance of a class.
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age) {
Name = name;
Age = age;
}
public void Greet() {
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
// Creating an object (instance) of the Person class
Person person1 = new Person("Alice", 30);
person1.Greet(); // Output: Hello, my name is Alice and I am 30 years old.
Interfaces
An interface defines a contract that classes can implement. It specifies a set of method signatures without providing any implementation. This promotes loose coupling.
public interface IAnimal {
void MakeSound();
}
public class Dog : IAnimal {
public void MakeSound() {
Console.WriteLine("Woof!");
}
}
Inheritance
Inheritance allows a class (derived class) to inherit properties and methods from another class (base class), promoting code reuse and a hierarchical structure.
public class Animal {
public virtual void Eat() {
Console.WriteLine("Eating...");
}
}
public class Cat : Animal {
public override void Eat() {
Console.WriteLine("Cats eat fish.");
}
}
Exception Handling
Exceptions are events that occur during program execution that disrupt the normal flow of instructions. .NET uses a structured exception handling mechanism.
try {
// Code that might throw an exception
int result = 10 / 0;
} catch (DivideByZeroException ex) {
Console.WriteLine("Error: Cannot divide by zero.");
// Log the exception details if needed
} finally {
// Code that always executes, regardless of whether an exception occurred
Console.WriteLine("Execution finished.");
}
Collections
Collections are used to store and manage groups of objects. The System.Collections.Generic
namespace provides powerful generic collections.
List<T>
: A resizable array.Dictionary<TKey, TValue>
: A collection of key-value pairs.HashSet<T>
: A collection of unique elements.
using System.Collections.Generic;
List<string> names = new List<string>();
names.Add("Bob");
names.Add("Charlie");
Dictionary<int, string> products = new Dictionary<int, string>();
products.Add(101, "Laptop");
products.Add(102, "Mouse");
Generics
Generics provide a way to create types and methods that operate on a variety of types without sacrificing type safety. This is achieved by using type parameters (e.g., <T>
).
Asynchronous Programming
Asynchronous programming allows your application to perform long-running operations without blocking the main thread, leading to more responsive user interfaces and efficient server applications. Key keywords are async
and await
.
public async Task<string> GetDataAsync() {
// Simulate a long-running operation
await Task.Delay(2000);
return "Data loaded!";
}
// In another method:
string result = await GetDataAsync();
Console.WriteLine(result);