Master advanced C# concepts and object-oriented programming principles.
Master advanced C# concepts and object-oriented programming principles.
Master object-oriented programming concepts including classes, objects, and inheritance in C#
Content by: Vaibhav Nakrani
.Net Developer
Classes are blueprints for creating objects. They define the structure and behavior that objects of that class will have. Objects are instances of classes that contain actual data and can perform actions.
// Class definition
public class Car
{
// Fields (attributes)
public string Brand { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public double Speed { get; set; }
// Constructor
public Car(string brand, string model, int year)
{
Brand = brand;
Model = model;
Year = year;
Speed = 0;
}
// Methods (behavior)
public void Accelerate(double increment)
{
Speed += increment;
Console.WriteLine($"{Brand} {Model} is now going {Speed} km/h");
}
public void Brake(double decrement)
{
Speed = Math.Max(0, Speed - decrement);
Console.WriteLine($"{Brand} {Model} slowed down to {Speed} km/h");
}
public void DisplayInfo()
{
Console.WriteLine($"Car: {Year} {Brand} {Model}");
}
}
// Creating objects
Car myCar = new Car("Toyota", "Camry", 2023);
Car yourCar = new Car("Honda", "Civic", 2022);
// Using objects
myCar.DisplayInfo();
myCar.Accelerate(50);
yourCar.Accelerate(30);
Test your understanding of this topic:
Learn polymorphism and interface implementation for flexible and maintainable code
Content by: Dipen Dalvadi
.Net Developer
Polymorphism allows objects of different types to be treated as objects of a common base type. It enables one interface to be used for a general class of actions.
// Interface definition
public interface IDrawable
{
void Draw();
double GetArea();
}
// Class implementing interface
public class Circle : IDrawable
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public void Draw()
{
Console.WriteLine($"Drawing a circle with radius {Radius}");
}
public double GetArea()
{
return Math.PI * Radius * Radius;
}
}
public class Rectangle : IDrawable
{
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
public void Draw()
{
Console.WriteLine($"Drawing a rectangle {Width}x{Height}");
}
public double GetArea()
{
return Width * Height;
}
}
// Using polymorphism
List<IDrawable> shapes = new List<IDrawable>
{
new Circle(5),
new Rectangle(4, 6),
new Circle(3)
};
foreach (IDrawable shape in shapes)
{
shape.Draw();
Console.WriteLine($"Area: {shape.GetArea()}");
}
Test your understanding of this topic:
Master generics and collections for type-safe and efficient data management
Content by: Sunny Radadiya
.Net Developer
Generics allow you to define type-safe classes, methods, and interfaces without specifying the actual data type until runtime. This provides better performance and type safety.
// Generic class
public class GenericRepository<T>
{
private List<T> items = new List<T>();
public void Add(T item)
{
items.Add(item);
}
public T GetById(int id)
{
return items[id];
}
public List<T> GetAll()
{
return new List<T>(items);
}
public void Remove(T item)
{
items.Remove(item);
}
}
// Generic method
public static class Utility
{
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
public static T Max<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
}
// Usage
GenericRepository<string> stringRepo = new GenericRepository<string>();
stringRepo.Add("Hello");
stringRepo.Add("World");
GenericRepository<int> intRepo = new GenericRepository<int>();
intRepo.Add(1);
intRepo.Add(2);
// Generic method usage
int x = 10, y = 20;
Utility.Swap(ref x, ref y);
Console.WriteLine($"x: {x}, y: {y}"); // x: 20, y: 10
Test your understanding of this topic:
Learn LINQ and lambda expressions for powerful data querying and manipulation
Content by: Akash Vadher
.Net Developer
Language Integrated Query (LINQ) provides a consistent way to query data from different sources. It allows you to write queries using C# syntax that work with collections, databases, and XML.
// Sample data
List<Person> people = new List<Person>
{
new Person { Name = "John", Age = 25, City = "New York" },
new Person { Name = "Jane", Age = 30, City = "Los Angeles" },
new Person { Name = "Bob", Age = 35, City = "New York" },
new Person { Name = "Alice", Age = 28, City = "Chicago" }
};
// LINQ Query Syntax
var adultsInNY = from person in people
where person.Age >= 18 && person.City == "New York"
orderby person.Name
select person;
// LINQ Method Syntax
var adultsInNY2 = people
.Where(p => p.Age >= 18 && p.City == "New York")
.OrderBy(p => p.Name)
.ToList();
// Lambda expressions
var names = people.Select(p => p.Name).ToList();
var averageAge = people.Average(p => p.Age);
var groupedByCity = people.GroupBy(p => p.City);
// More complex queries
var result = people
.Where(p => p.Age > 25)
.GroupBy(p => p.City)
.Select(g => new { City = g.Key, Count = g.Count() })
.OrderByDescending(x => x.Count)
.ToList();
Test your understanding of this topic:
Master asynchronous programming with async/await for responsive applications
Content by: Vaibhav Nakrani
.Net Developer
Async/await allows you to write asynchronous code that looks like synchronous code. It helps prevent blocking operations and improves application responsiveness.
// Async method example
public async Task<string> FetchDataAsync(string url)
{
using (HttpClient client = new HttpClient())
{
try
{
string result = await client.GetStringAsync(url);
return result;
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Error fetching data: {ex.Message}");
return null;
}
}
}
// Multiple async operations
public async Task<List<string>> FetchMultipleDataAsync(List<string> urls)
{
var tasks = urls.Select(url => FetchDataAsync(url));
var results = await Task.WhenAll(tasks);
return results.Where(r => r != null).ToList();
}
// Async with cancellation
public async Task<string> FetchDataWithCancellationAsync(string url, CancellationToken cancellationToken)
{
using (HttpClient client = new HttpClient())
{
try
{
string result = await client.GetStringAsync(url, cancellationToken);
return result;
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was cancelled");
return null;
}
}
}
// Usage
async Task Main()
{
string data = await FetchDataAsync("https://api.example.com/data");
Console.WriteLine(data);
var urls = new List<string> { "url1", "url2", "url3" };
var results = await FetchMultipleDataAsync(urls);
Console.WriteLine($"Fetched {results.Count} items");
}
Test your understanding of this topic:
Learn proper exception handling techniques for robust applications
Content by: Vaibhav Nakrani
.Net Developer
Exception handling allows you to gracefully handle errors and unexpected situations in your code. It prevents application crashes and provides better user experience.
// Basic exception handling
try
{
int result = Divide(10, 0);
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
Console.WriteLine("This always executes");
}
// Custom exceptions
public class CustomException : Exception
{
public CustomException(string message) : base(message) { }
public CustomException(string message, Exception innerException) : base(message, innerException) { }
}
// Throwing exceptions
public int Divide(int a, int b)
{
if (b == 0)
{
throw new DivideByZeroException("Cannot divide by zero");
}
return a / b;
}
// Using custom exceptions
public void ProcessData(string data)
{
if (string.IsNullOrEmpty(data))
{
throw new CustomException("Data cannot be null or empty");
}
try
{
// Process data
Console.WriteLine($"Processing: {data}");
}
catch (Exception ex)
{
throw new CustomException("Error processing data", ex);
}
}
Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 3