0% found this document useful (0 votes)
8 views8 pages

Training Documentation

The document provides a comprehensive overview of C# programming concepts including classes, objects, data types, operators, methods, control flow statements, loops, arrays, collections, LINQ, and exception handling. It includes examples for each concept to illustrate their usage and functionality. Additionally, it covers custom exceptions and middleware for exception handling in ASP.NET Core.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

Training Documentation

The document provides a comprehensive overview of C# programming concepts including classes, objects, data types, operators, methods, control flow statements, loops, arrays, collections, LINQ, and exception handling. It includes examples for each concept to illustrate their usage and functionality. Additionally, it covers custom exceptions and middleware for exception handling in ASP.NET Core.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Training Documentation

1. Class, Object, Datatypes, Operators, Void Method


Class: A class is like a blueprint for creating objects. It defines properties (variables) and
methods (functions) that an object will have.
Example:
class Car
{
public string brand = "Toyota"; // Property
}
Object: An object is an instance of a class. It is created using the new keyword.
Example:
Car myCar = new Car();
Console.WriteLine(myCar.brand);
Data Types:

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
}
}

3. Models, Method with models as parameter

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; }
}

Method with Model as a Parameter: You can pass a model as a parameter to a


method. This allows you to send multiple pieces of related data in a structured way.
Example:
class Program
{
static void PrintPersonDetails(Person person)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
static void Main()
{
Person p = new Person { Name = "Alice", Age = 25 };
PrintPersonDetails(p);
}
}

4. Control flow statements, Loops

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. while loop - Repeats a block of code while a condition is true.


Example:
int i = 1;
while (i <= 5)
{
Console.WriteLine("Count: " + i);
i++;
}
c. do-while loop - Executes the loop at least once, even if the condition is false.
Example:
int i = 1;
do
{
Console.WriteLine("Hello");
i++;
} while (i <= 3);

d. foreach loop - Used to loop through arrays or collections.


Example:
string[] fruits = { "Apple", "Banana", "Mango" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}

5. Arrays, Generic collections (Lists), LINQ

Arrays: An array is a collection of elements of the same data type, stored in


contiguous memory locations.
a. Declaring and Initializing an Array
int[] numbers = { 10, 20, 30, 40, 50 };

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();

6. Exception Handling and middleware, Custom Exceptions

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>();

You might also like