Top 100 C# (C-sharp) Interview Programs with Answers
1. Hello World Program:
using System;
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello,
World!");
}
}
2. Variables and Data Types:
using System;
class VariablesAndDataTypes
{
static void Main(string[] args)
{
int age = 25;
double salary = 50000.50;
string name = "John";
Console.WriteLine($"Name: {name},
Age: {age}, Salary: {salary}");
}
}
3. Arithmetic Operations:
using System;
class ArithmeticOperations
{
static void Main(string[] args)
{
int num1 = 10;
int num2 = 5;
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
double quotient = (double)num1 / num2;
Console.WriteLine($"Sum: {sum},
Difference: {difference}, Product: {product}, Quotient: {quotient}");
}
}
4. Conditional Statements (if-else):
using System;
class ConditionalStatements
{
static void Main(string[] args)
{
int num = 10;
if (num > 0)
{
Console.WriteLine("Number is
positive.");
}
else if (num < 0)
{
Console.WriteLine("Number is
negative.");
}
else
{
Console.WriteLine("Number is
zero.");
}
}
}
5. Loops (for, while):
using System;
class Loops
{
static void Main(string[] args)
{
// For loop
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"For loop
iteration: {i}");
}
// While loop
int j = 1;
while (j <= 5)
{
Console.WriteLine($"While loop
iteration: {j}");
j++;
}
}
}
6. Basic Input/Output:
using System;
class BasicIO
{
static void Main(string[] args)
{
Console.Write("Enter your name:
");
string name = Console.ReadLine();
Console.WriteLine($"Hello,
{name}!");
}
}
7. Arrays and Lists:
7.1 Finding the largest element in an array:
using System;
class LargestElement
{
static void Main(string[] args)
{
int[] numbers = { 10, 5, 20, 15, 25 };
int max = numbers[0];
foreach (int num in numbers)
{
if (num > max)
{
max = num;
}
}
Console.WriteLine($"The largest
element is: {max}");
}
}
7.2 Reversing an array:
using System;
class ReverseArray
{
static void Main(string[] args)
{
int[] numbers = { 10, 20, 30, 40, 50 };
int[] reversed = new
int[numbers.Length];
for (int i = 0; i < numbers.Length;
i++)
{
reversed[numbers.Length - 1 - i] =
numbers[i];
}
Console.Write("Reversed array:
");
foreach (int num in reversed)
{
Console.Write($"{num} ");
}
}
}
7.3 Finding duplicates in an array:
using System;
class FindDuplicates
{
static void Main(string[] args)
{
int[] numbers = { 2, 3, 4, 2, 7, 8, 4
};
Console.Write("Duplicate elements:
");
for (int i = 0; i < numbers.Length;
i++)
{
for (int j = i + 1; j <
numbers.Length; j++)
{
if (numbers[i] == numbers[j])
{
Console.Write($"{numbers[i]} ");
break;
}
}
}
}
}
7.4 Implementing a stack using an array:
using System;
class StackUsingArray
{
private int maxSize;
private int[] stackArray;
private int top;
public StackUsingArray(int size)
{
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void Push(int value)
{
if (top < maxSize - 1)
{
stackArray[++top] = value;
}
else
{
Console.WriteLine("Stack is
full. Cannot push element.");
}
}
public int Pop()
{
if (top >= 0)
{
return stackArray[top--];
}
else
{
Console.WriteLine("Stack is
empty. Cannot pop element.");
return -1;
}
}
public void PrintStack()
{
Console.Write("Stack: ");
for (int i = 0; i <= top; i++)
{
Console.Write($"{stackArray[i]} ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
StackUsingArray stack = new
StackUsingArray(5);
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.PrintStack();
int poppedValue = stack.Pop();
Console.WriteLine($"Popped value:
{poppedValue}");
stack.PrintStack();
}
}
7.5 Implementing a queue using an array:
using System;
class QueueUsingArray
{
private int maxSize;
private int[] queueArray;
private int front;
private int rear;
private int itemCount;
public QueueUsingArray(int size)
{
maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1;
itemCount = 0;
}
public void Enqueue(int value)
{
if (itemCount < maxSize)
{
if (rear == maxSize - 1)
{
rear = -1;
}
queueArray[++rear] = value;
itemCount++;
}
else
{
Console.WriteLine("Queue is
full. Cannot enqueue element.");
}
}
public int Dequeue()
{
if (itemCount > 0)
{
int dequeuedValue =
queueArray[front++];
if (front == maxSize)
{
front = 0;
}
itemCount--;
return dequeuedValue;
}
else
{
Console.WriteLine("Queue is
empty. Cannot dequeue element.");
return -1;
}
}
public void PrintQueue()
{
Console.Write("Queue: ");
for (int i = 0; i < itemCount; i++)
{
int index = (front +
i) % maxSize;
Console.Write($"{queueArray[index]} ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
QueueUsingArray queue = new
QueueUsingArray(5);
queue.Enqueue(10);
queue.Enqueue(20);
queue.Enqueue(30);
queue.PrintQueue();
int dequeuedValue = queue.Dequeue();
Console.WriteLine($"Dequeued
value: {dequeuedValue}");
queue.PrintQueue();
}
}
7.6 Working with Lists (Add, Remove, Search):
using System;
using
System.Collections.Generic;
class ListsExample
{
static void Main(string[] args)
{
List<string> names = new
List<string>();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
Console.WriteLine("List
contents:");
foreach (string name in names)
{
Console.WriteLine(name);
}
names.Remove("Bob");
Console.WriteLine("\nList after
removing 'Bob':");
foreach (string name in names)
{
Console.WriteLine(name);
}
if
(names.Contains("Charlie"))
{
Console.WriteLine("\n'Charlie'
found in the list.");
}
else
{
Console.WriteLine("\n'Charlie'
not found in the list.");
}
}
}
8. Strings:
8.1 Reversing a string:
using System;
class ReverseString
{
static void Main(string[] args)
{
string input = "Hello,
World!";
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
string reversed = new
string(charArray);
Console.WriteLine($"Reversed
string: {reversed}");
}
}
8.2 Checking if a string is a palindrome:
using System;
class PalindromeCheck
{
static bool IsPalindrome(string str)
{
int left = 0;
int right = str.Length - 1;
while (left < right)
{
if (str[left] != str[right])
{
return false;
}
left++;
right--;
}
return true;
}
static void Main(string[] args)
{
string input = "racecar";
if (IsPalindrome(input))
{
Console.WriteLine($"{input} is
a palindrome.");
}
else
{
Console.WriteLine($"{input} is
not a palindrome.");
}
}
}
8.3 Counting occurrences of a character:
using System;
class CountOccurrences
{
static void Main(string[] args)
{
string input = "programming";
char target = 'r';
int count = 0;
foreach (char c in input)
{
if (c == target)
{
count++;
}
}
Console.WriteLine($"Occurrences of
'{target}' in '{input}': {count}");
}
}
8.4 Finding the first non-repeated character:
using System;
using
System.Collections.Generic;
class FirstNonRepeated
{
static char FindFirstNonRepeated(string
str)
{
Dictionary<char, int> charCount =
new Dictionary<char, int>();
foreach (char c in str)
{
if (charCount.ContainsKey(c))
{
charCount[c]++;
}
else
{
charCount[c] = 1;
}
}
foreach (char c in str)
{
if (charCount[c] == 1)
{
return c;
}
}
return '\0';
}
static void Main(string[] args)
{
string input = "hello";
char result =
FindFirstNonRepeated(input);
if (result != '\0')
{
Console.WriteLine($"First
non-repeated character: {result}");
}
else
{
Console.WriteLine("No
non-repeated character found.");
}
}
}
8.5 String manipulation (concatenation, substring):
using System;
class StringManipulation
{
static void Main(string[] args)
{
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + "
" + lastName;
Console.WriteLine($"Full name:
{fullName}");
string sentence = "The quick brown
fox jumps over the lazy dog";
string sub = sentence.Substring(4, 15);
// Extract "quick brown fox"
Console.WriteLine($"Substring:
{sub}");
}
}
8.6 Anagram detection:
using System;
class AnagramCheck
{
static bool AreAnagrams(string str1, string
str2)
{
if (str1.Length != str2.Length)
{
return false;
}
int[] charCount = new int[256];
foreach (char c in str1)
{
charCount[c]++;
}
foreach (char c in str2)
{
charCount[c]--;
}
foreach (int count in charCount)
{
if (count != 0)
{
return false;
}
}
return true;
}
static void Main(string[] args)
{
string word1 = "listen";
string word2 = "silent";
if (AreAnagrams(word1, word2))
{
Console.WriteLine($"{word1}
and {word2} are anagrams.");
}
else
{
Console.WriteLine($"{word1}
and {word2} are not anagrams.");
}
}
}
9. Functions and Methods:
9.1 Creating and calling a function:
using System;
class FunctionsExample
{
static void Greet()
{
Console.WriteLine("Hello,
there!");
}
static void Main(string[] args)
{
Greet();
}
}
9.2 Function with parameters and return value:
using System;
class FunctionWithParameters
{
static int Add(int num1, int num2)
{
return num1 + num2;
}
static void Main(string[] args)
{
int result = Add(5, 10);
Console.WriteLine($"Result:
{result}");
}
}
9.3 Recursive functions (factorial, Fibonacci):
using System;
class RecursiveFunctions
{
static int Factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
return n * Factorial(n - 1);
}
static int Fibonacci(int n)
{
if (n <= 1)
{
return n;
}
return Fibonacci(n - 1) + Fibonacci(n -
2);
}
static void Main(string[] args)
{
int num = 5;
Console.WriteLine($"Factorial of
{num}: {Factorial(num)}");
Console.WriteLine($"Fibonacci of
{num}: {Fibonacci(num)}");
}
}
9.4 Method overloading:
using System;
class MethodOverloading
{
static int Add(int num1, int num2)
{
return num1 + num2;
}
static double Add(double num1, double num2)
{
return num1 + num2;
}
static string Add(string str1, string str2)
{
return str1 + str2;
}
static void Main(string[] args)
{
Console.WriteLine($"Int addition:
{Add(5, 10)}");
Console.WriteLine($"Double
addition: {Add(3.14, 2.71)}");
Console.WriteLine($"String
concatenation: {Add("Hello, ", "World!")}");
}
}
9.5 Method overriding:
using System;
class MethodOverriding
{
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a
shape.");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a
circle.");
}
}
static void Main(string[] args)
{
Shape shape = new Shape();
shape.Draw();
Circle circle = new Circle();
circle.Draw();
}
}
10. Object-Oriented Programming:
10.1 Class and Object:
using System;
class Car
{
public string Model { get; set; }
public int Year { get; set; }
public void StartEngine()
{
Console.WriteLine($"Starting the
engine of {Model}...");
}
}
class OOPExample
{
static void Main(string[] args)
{
Car myCar = new Car();
myCar.Model = "Toyota Camry";
myCar.Year = 2023;
Console.WriteLine($"Car:
{myCar.Model}, Year: {myCar.Year}");
myCar.StartEngine();
}
}
10.2 Inheritance:
using System;
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a
shape.");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a
circle.");
}
}
class InheritanceExample
{
static void Main(string[] args)
{
Shape shape = new Shape();
shape.Draw();
Circle circle = new Circle();
circle.Draw();
}
}
10.3 Encapsulation:
using System;
class BankAccount
{
private double balance;
public void Deposit(double amount)
{
if (amount > 0)
{
balance += amount;
}
}
public void Withdraw(double amount)
{
if (amount > 0 && balance
>= amount)
{
balance -= amount;
}
}
public double GetBalance()
{
return balance;
}
}
class EncapsulationExample
{
static void Main(string[] args)
{
BankAccount account = new
BankAccount();
account.Deposit(1000);
account.Withdraw(500);
Console.WriteLine($"Account
balance: {account.GetBalance()}");
}
}
Object-Oriented Programming:
24. Creating a class and object
using System;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "John";
person.Age = 30;
Console.WriteLine($"Name: {person.Name},
Age: {person.Age}");
}
}
25. Constructors and destructors
using System;
class Car
{
public Car()
{
Console.WriteLine("Car constructor
called.");
}
~Car()
{
Console.WriteLine("Car destructor
called.");
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();
// Other code...
}
}
26. Inheritance and base class
using System;
class Vehicle
{
public void StartEngine()
{
Console.WriteLine("Engine
started.");
}
}
class Car : Vehicle
{
public void Accelerate()
{
Console.WriteLine("Car is
accelerating.");
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();
myCar.StartEngine();
myCar.Accelerate();
}
}
27. Polymorphism and method overriding
using System;
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a
shape.");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a
circle.");
}
}
class Program
{
static void Main(string[] args)
{
Shape shape = new Circle();
shape.Draw();
}
}
28. Abstract classes and interfaces
using System;
abstract class Shape
{
public abstract void Draw();
}
interface IResizable
{
void Resize();
}
class Circle : Shape,
IResizable
{
public override void Draw()
{
Console.WriteLine("Drawing a
circle.");
}
public void Resize()
{
Console.WriteLine("Resizing the
circle.");
}
}
class Program
{
static void Main(string[] args)
{
Circle circle = new Circle();
circle.Draw();
circle.Resize();
}
}
29. Encapsulation and access modifiers
using System;
class BankAccount
{
private double balance;
public void Deposit(double amount)
{
if (amount > 0)
balance += amount;
}
public double GetBalance()
{
return balance;
}
}
class Program
{
static void Main(string[] args)
{
BankAccount account = new
BankAccount();
account.Deposit(1000);
Console.WriteLine($"Balance:
{account.GetBalance()}");
}
}
Exception Handling:
30. Handling exceptions (try-catch)
using System;
class Program
{
static void Main(string[] args)
{
try
{
int num =
int.Parse(Console.ReadLine());
int result = 10 / num;
Console.WriteLine($"Result:
{result}");
}
catch (DivideByZeroException)
{
Console.WriteLine("Cannot
divide by zero.");
}
catch (FormatException)
{
Console.WriteLine("Invalid
input format.");
}
catch (Exception ex)
{
Console.WriteLine($"An error
occurred: {ex.Message}");
}
}
}
31. Custom exceptions
using System;
class CustomException :
Exception
{
public CustomException(string message) :
base(message)
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
throw new
CustomException("Custom exception occurred.");
}
catch (CustomException ex)
{
Console.WriteLine($"Custom
exception caught: {ex.Message}");
}
}
}
32. Finally block usage
using System;
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Try
block.");
}
catch (Exception)
{
Console.WriteLine("Catch
block.");
}
finally
{
Console.WriteLine("Finally
block.");
}
}
}
33. Exception propagation
using System;
class Program
{
static void Method1()
{
throw new Exception("Exception
from Method1.");
}
static void Method2()
{
Method1();
}
static void Main(string[] args)
{
try
{
Method2();
}
catch (Exception ex)
{
Console.WriteLine($"Exception
caught: {ex.Message}");
}
}
}
File Handling:
34. Reading from a file
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath =
"sample.txt";
if (File.Exists(filePath))
{
string content =
File.ReadAllText(filePath);
Console.WriteLine(content);
}
else
{
Console.WriteLine("File not
found.");
}
}
}
35. Writing to a file
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath =
"output.txt";
string content = "Hello, this is
written to a file.";
File.WriteAllText(filePath, content);
Console.WriteLine("Content written
to the file.");
}
}
36. File manipulation (rename, delete)
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string oldFilePath =
"oldfile.txt";
string newFilePath =
"newfile.txt";
if (File.Exists(oldFilePath))
{
File.Move(oldFilePath,
newFilePath);
Console.WriteLine("File
renamed.");
}
if (File.Exists(newFilePath))
{
File.Delete(newFilePath);
Console.WriteLine("File
deleted.");
}
}
}
37. Working with directories
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string directoryPath =
"MyDirectory";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
Console.WriteLine("Directory
created.");
}
string[] files = Directory.GetFiles(directoryPath);
Console.WriteLine($"Files in the
directory: {string.Join(", ", files)}");
Directory.Delete(directoryPath);
Console.WriteLine("Directory
deleted.");
}
}
Collections and Generics:
38. Working with dictionaries
using System;
using
System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> ages =
new Dictionary<string, int>();
ages["John"] = 30;
ages
["Jane"] = 25;
foreach (var kvp in ages)
{
Console.WriteLine($"{kvp.Key}:
{kvp.Value} years old");
}
}
}
39. Working with hashsets
using System;
using
System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
HashSet<string> names = new HashSet<string>();
names.Add("John");
names.Add("Jane");
names.Add("John"); //
Duplicate entry, ignored by HashSet
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
40. Using generic classes
using System;
class MyGenericClass<T>
{
public T Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyGenericClass<int> intContainer
= new MyGenericClass<int>();
intContainer.Value = 42;
MyGenericClass<string>
stringContainer = new MyGenericClass<string>();
stringContainer.Value = "Hello,
generics!";
Console.WriteLine(intContainer.Value);
Console.WriteLine(stringContainer.Value);
}
}
41. Using generic methods
using System;
class Program
{
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
int num1 = 10, num2 = 20;
Console.WriteLine($"Before swap: num1 =
{num1}, num2 = {num2}");
Swap(ref num1, ref num2);
Console.WriteLine($"After swap:
num1 = {num1}, num2 = {num2}");
}
}
42. Creating custom generic classes
using System;
class MyGenericClass<T1,
T2>
{
public T1 Item1 { get; set; }
public T2 Item2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyGenericClass<int, string>
myPair = new MyGenericClass<int, string>();
myPair.Item1 = 42;
myPair.Item2 = "Hello, generics
pair!";
Console.WriteLine($"Item1:
{myPair.Item1}, Item2: {myPair.Item2}");
}
}
LINQ (Language Integrated Query):
43. Filtering and sorting data
using System;
using System.Linq;
using
System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new
List<int> { 5, 2, 8, 1, 7, 3 };
var filteredAndSorted = numbers.Where(n
=> n > 3).OrderBy(n => n);
foreach (var num in filteredAndSorted)
{
Console.WriteLine(num);
}
}
}
44. Projection and transformation
using System;
using System.Linq;
using
System.Collections.Generic;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> people = new
List<Person>
{
new Person { Name =
"John", Age = 30 },
new Person { Name =
"Jane", Age = 25 }
};
var names = people.Select(p =>
p.Name);
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
45. Joining multiple data sources
using System;
using System.Linq;
using
System.Collections.Generic;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Address
{
public string City { get; set; }
public string Country { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> people = new
List<Person>
{
new Person { Name =
"John", Age = 30 },
new Person { Name =
"Jane", Age = 25 }
};
List<Address> addresses = new
List<Address>
{
new Address { City = "New
York", Country = "USA" },
new Address { City =
"London", Country = "UK" }
};
var joinedData = people.Join(
addresses,
person => person.Name,
address => address.City,
(person, address) => new {
person.Name, person.Age, address.Country });
foreach (var item in joinedData)
{
Console.WriteLine($"{item.Name}, {item.Age}, {item.Country}");
}
}
}
46. Grouping and aggregation
using System;
using System.Linq;
using
System.Collections.Generic;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> people = new
List<Person>
{
new Person { Name =
"John", Age = 30 },
new Person { Name =
"Jane", Age = 25 },
new Person { Name =
"Alice", Age = 30 }
};
var groupedData = people.GroupBy(p
=> p.Age);
foreach (var group in groupedData)
{
Console.WriteLine($"Age:
{group.Key}");
foreach (var person in group)
{
Console.WriteLine($"-
{person.Name}");
}
}
}
}
Multithreading:
47. Creating and starting a thread:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(new
ThreadStart(DoWork));
thread.Start();
}
static void DoWork()
{
Console.WriteLine("Thread is
working.");
}
}
48. Synchronization using locks:
using System;
using System.Threading;
class Program
{
static int counter = 0;
static object lockObject = new object();
static void Main(string[] args)
{
Thread thread1 = new
Thread(IncrementCounter);
Thread thread2 = new
Thread(IncrementCounter);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine("Final counter
value: " + counter);
}
static void IncrementCounter()
{
for (int i = 0; i < 10000; i++)
{
lock (lockObject)
{
counter++;
}
}
}
}
49. Thread safety and race conditions:
// Similar to the code
provided in the previous section (Synchronization using locks)
// This example shows how
locks can help prevent race conditions
50. Background vs Foreground threads:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Thread foregroundThread = new
Thread(new ThreadStart(DoWork));
Thread backgroundThread = new
Thread(new ThreadStart(DoWork));
foregroundThread.IsBackground = false;
// Foreground thread
backgroundThread.IsBackground =
true; // Background thread
foregroundThread.Start();
backgroundThread.Start();
Console.WriteLine("Main thread
exiting.");
}
static void DoWork()
{
Thread.Sleep(1000); // Simulate some
work
Console.WriteLine("Thread
completed.");
}
}
51. Using Task and async/await:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
await DoWorkAsync();
}
static async Task DoWorkAsync()
{
Console.WriteLine("Starting
asynchronous work.");
await Task.Delay(1000); // Simulate
asynchronous work
Console.WriteLine("Asynchronous
work completed.");
}
}
Delegates and Events:
52. Creating and invoking delegates:
using System;
class Program
{
delegate void MyDelegate(string message);
static void Main(string[] args)
{
MyDelegate myDelegate = new
MyDelegate(PrintMessage);
myDelegate("Hello,
delegates!");
}
static void PrintMessage(string message)
{
Console.WriteLine(message);
}
}
53. Multicast delegates:
using System;
class Program
{
delegate void MyDelegate(string message);
static void Main(string[] args)
{
MyDelegate myDelegate = PrintMessage1;
myDelegate += PrintMessage2;
myDelegate("Multicast
delegates");
}
static void PrintMessage1(string message)
{
Console.WriteLine("Message from
delegate 1: " + message);
}
static void PrintMessage2(string message)
{
Console.WriteLine("Message from
delegate 2: " + message);
}
}
54. Creating and raising events:
using System;
class Program
{
class EventPublisher
{
public event
EventHandler<MyEventArgs> MyEvent;
public void RaiseEvent(string message)
{
MyEvent?.Invoke(this, new
MyEventArgs(message));
}
}
class MyEventArgs : EventArgs
{
public string Message { get; }
public MyEventArgs(string message)
{
Message = message;
}
}
static void Main(string[] args)
{
EventPublisher publisher = new
EventPublisher();
publisher.MyEvent += EventSubscriber;
publisher.RaiseEvent("Event
raised!");
}
static void EventSubscriber(object sender,
MyEventArgs e)
{
Console.WriteLine("Event received:
" + e.Message);
}
}
55. Event subscribers and publishers:
// Similar to the code
provided in the previous section (Creating and raising events)
// This example demonstrates
how event subscribers can listen to events raised by publishers
Serialization:
56. Serialization and deserialization of objects:
using System;
using System.IO;
using
System.Runtime.Serialization;
using
System.Runtime.Serialization.Formatters.Binary;
class Program
{
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main(string[] args)
{
Person person = new Person { Name =
"John", Age = 30 };