Training Documentation
Training Documentation
DataType Example
int int x = 10;
float float y = 10.5f;
double double z = 99.99;
char char grade = 'A';
string string name = "John";
bool bool isActive = true;
Operators:
a. Arithmetic Operators:
int a = 10, b = 5;
Console.WriteLine(a + b); // Output: 15
Console.WriteLine(a - b); // Output: 5
Console.WriteLine(a * b); // Output: 50
Console.WriteLine(a / b); // Output: 2
Console.WriteLine(a % b); // Output: 0 (remainder)
b. Comparison Operators:
Console.WriteLine(a > b); // Output: True
Console.WriteLine(a == b); // Output: False
c. Logical Operators:
bool x = true, y = false;
Console.WriteLine(x && y); // Output: False (AND operator)
Console.WriteLine(x || y); // Output: True (OR operator)
Console.WriteLine(!x); // Output: False (NOT operator)
Void Method: A void method is a method that does not return any value.
Example:
class Program
{
static void Greet() // Method with void (no return)
{
Console.WriteLine("Hello, Welcome!");
}
static void Main()
{
Greet(); // Calling the method
}
}
2. Method with return type, Method with different data types as parameters,
Dynamic
Method with Return Type: A method with a return type returns a value after
performing an operation.
Example:
class Program
{
static int Add(int a, int b) // Method with return type int
{
return a + b;
}
static void Main()
{
int result = Add(5, 3);
Console.WriteLine(result); // Output: 8
}
}
Method with Different Data Types as Parameters: Passing different data types as
parameters to a method.
Example:
class Program
{
static void ShowDetails(string name, int age, bool isStudent)
{
Console.WriteLine($"Name: {name}, Age: {age}, Student: {isStudent}");
}
static void Main()
{
ShowDetails("John", 21, true);
}
}
Dynamic Data Type (dynamic): The dynamic keyword allows a variable to hold
any type of value. The type is determined at runtime.
Example:
class Program
{
static void Main()
{
dynamic data = 10; // Initially an int
Console.WriteLine(data); // Output: 10
data = "Hello"; // Now a string
Console.WriteLine(data); // Output: Hello
data = 3.14; // Now a double
Console.WriteLine(data); // Output: 3.14
}
}
Models in C#: A Model is a class that represents data. It is used to store and manage
data in an organized way.
Example:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Control Flow Statements: Control flow statements decide the flow of execution in a
program based on conditions.
a. if-else - Executes different code blocks based on conditions.
Example:
int num = 10;
if (num > 0)
{
Console.WriteLine("Positive Number");
}
else
{
Console.WriteLine("Negative Number");
}
b. switch-case - Used when there are multiple conditions.
Example:
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid Day");
break;
}
c. ternary operator (? :) - A shortcut for if-else
Example:
int age = 20;
string result = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine(result);
Loops: Loops are used to execute code repeatedly.
a. for loop - Repeats a block of code a fixed number of times.
Example:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Number: " + i);
}
b. Accessing Elements
Console.WriteLine(numbers[0]); // Output: 10
Console.WriteLine(numbers[2]); // Output: 30
c. Looping Through an Array
foreach (int num in numbers)
{
Console.WriteLine(num);
}
Generic Collections (Lists): A List<T> is a dynamic collection that can grow or shrink
at runtime (unlike arrays, which have a fixed size).
class Program
{
static void PrintList<T>(List<T> items)
{
foreach (T item in items)
{
Console.WriteLine(item);
}
}
static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
PrintList(names);
}
}
LINQ:
List<int> numbers = new List<int> { 10, 20, 30 };
a. Filtering: Where()
List<int> result = numbers.Where(n => n > 10);
b. Sorting: OrderBy(), OrderByDescending()
List<int> ascendingOrder = numbers.OrderBy(n => n);
List<int> descendingOrder = numbers.OrderByDescending(n => n);
c. Projection (Selecting Data): Select()
List<int> squaredNumbers = numbers.Select(n => n * n);
d. Aggregation: Sum(), Count(), Average(), Min(), Max()
List<int> totalSum = numbers.Sum();
List<int> totalCount = numbers.Count();
List<int> averageValue = numbers.Average();
List<int> minValue = numbers.Min();
List<int> maxValue = numbers.Max();
e. Grouping: GroupBy()
List<string> groupedData = names.GroupBy(n => n[0]); // Group by first letter
f. Quantifiers: Any(), All()
List<int> hasLargeNumbers = numbers.Any(n => n > 50);
List<int> allArePositive = numbers.All(n => n > 0);
g. Set Operations: Distinct(), Union(), Except(), Intersect()
List<int> uniqueNumbers = numbers.Distinct();
List<int> combinedLists = list1.Union(list2);
List<int> differentNumbers = list1.Except(list2);
List<int> commonNumbers = list1.Intersect(list2);
h. Conversion: ToList(), ToArray()
List<int> list = numbers.ToList();
List<int> array = numbers.ToArray();
Exception Handling in C#: Exception handling is used to manage runtime errors and
prevent program crashes. (Basic Try-Catch-Finally)
Example:
try
{
int result = 10 / 0; // Will throw a DivideByZeroException
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
Console.WriteLine("Execution completed.");
}
Custom Exception Handling: You can define your own exception by extending
Exception class.
Example:
class CustomException : Exception
{
public CustomException(string message) : base(message) { }
}
try
{
throw new CustomException("This is a custom error!");
}
catch (CustomException ex)
{
Console.WriteLine(ex.Message);
}
Middleware for Exception Handling in ASP.NET Core: Middleware is a piece of code
that runs in the request-response pipeline. You can create middleware to handle
exceptions globally.
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
public ExceptionHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync($"Something went wrong:
{ex.Message}");
}
}
}
//Register in Program.cs
app.UseMiddleware<ExceptionHandlingMiddleware>();