0% found this document useful (0 votes)
18 views47 pages

.Net Full Stack Angular&React Batches - Question 2

Uploaded by

Ven Cut Ramesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views47 pages

.Net Full Stack Angular&React Batches - Question 2

Uploaded by

Ven Cut Ramesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Topic

Introduction to .NET and C# Fundamentals


OOP - Classes and Objects, OOPs Language Specific Features
OOP - Inheritance, Polymorphism, Interfaces
Exception Handling and File I/O
Collections and Generics
Question 1: Data Types

Scenario: You are working on a financial application that calculates monthly salary for employees. Yo

Question: Which of the following data types is best suited for representing the monthly salary of emp

A) int

B) float

C) decimal

D) double

Answer: C) decimal

Question 2: var Keyword

Scenario: In a web application, you are dynamically fetching user data from a database. The exact ty

Question: Which of the following statements correctly demonstrates how to use the var keyword to d

A) var userData = GetUserData();

B) var int userData = GetUserData();

C) var string userData = GetUserData();

D) var dynamic userData = GetUserData();

Answer: A) var userData = GetUserData();

Question 3: dynamic Keyword

Scenario: You are developing a plugin system where the types of objects being processed are only k

Question: Which of the following code snippets correctly demonstrates the use of the dynamic keywo

A) dynamic plugin = GetPlugin();

B) var plugin = dynamic GetPlugin();

C) dynamic plugin = (dynamic)GetPlugin();


D) var dynamic plugin = GetPlugin();

Answer: A) dynamic plugin = GetPlugin();

Question 4: Constants

Scenario: You are defining the maximum number of users that can be registered in an application. T

Question: How do you declare this value as a constant in C#?

A) const int maxUsers = 100;

B) static int maxUsers = 100;

C) readonly int maxUsers = 100;

D) fixed int maxUsers = 100;

Answer: A) const int maxUsers = 100;

Question 5: Type Casting

Scenario: You have a list of objects representing different types of documents. You need to cast one

Question: Which of the following statements correctly demonstrates explicit type casting in C#?

A) Document doc = (Document)documents[0];

B) Document doc = documents[0] as Document;

C) Document doc = documents[0];

D) Document doc = (dynamic)documents[0];

Answer: A) Document doc = (Document)documents[0];

Question 6: Int.Parse()

Scenario: You are reading numerical input from a text field in a web form and need to convert it to a

Question: Which of the following code snippets correctly demonstrates the use of Int.Parse() to conve
A) int value = Int.Parse(textField.Text);

B) int value = textField.Text.Parse();

C) int value = Parse.Int(textField.Text);

D) int value = textField.Text.IntParse();

Answer: A) int value = Int.Parse(textField.Text);

Question 7: int.TryParse()

Scenario: You need to validate user input from a text field and ensure it can be successfully converte

Question: Which of the following code snippets correctly demonstrates the use of int.TryParse()?

A) bool result = int.TryParse(textField.Text, out int value);

B) bool result = textField.Text.TryParse(out int value);

C) bool result = int.TryParse(out int value, textField.Text);

D) bool result = TryParse(int, textField.Text, out int value);

Answer: A) bool result = int.TryParse(textField.Text, out int value);

Question 8: Boxing

Scenario: You need to store an integer value in an object type variable to pass it to a method that ac

Question: Which of the following code snippets correctly demonstrates boxing in C#?

A) object obj = 42;

B) int value = 42; object obj = value;

C) object obj = (object)42;

D) int value = 42; object obj = (object)value;

Answer: D) int value = 42; object obj = (object)value;


Question 9: Unboxing

Scenario: You have an object type variable that contains a boxed integer, and you need to retrieve t

Question: Which of the following code snippets correctly demonstrates unboxing in C#?

A) int value = obj;

B) int value = (int)obj;

C) int value = (object)obj;

D) int value = (dynamic)obj;

Answer: B) int value = (int)obj;

1. Scenario: Class Instantiation

Question:
Which code snippet correctly creates an instance of the Person class and initializes its Name property?

A) Person person = new Person { Name = "John" };


B) Person person = new Person(Name = "John");
C) Person person = new Person(); person.Name = "John";
D) Person person = new Person { "John" };

Answer:
A) Person person = new Person { Name = "John" };

2. Scenario: Default Constructor

Question:
What will be the output of the following code snippet?

csharp
Copy code
public class Book
{
public string Title { get; set; }

public Book()
{
Title = "Unknown Title";
}
}
// Usage
Book book = new Book();
Console.WriteLine(book.Title);

A) Unknown Title
B) Title
C) null
D) Compilation error

Answer:
A) Unknown Title

3. Scenario: Private Fields

Question:
Which code snippet demonstrates correct usage of private fields and public properties in a Car class?

csharp
Copy code
public class Car
{
private string model;
public string Model
{
get { return model; }
set { model = value; }
}
}

// Usage

A) Car car = new Car(); car.Model = "Sedan"; Console.WriteLine(car.Model);


B) Car car = new Car(); car.model = "Sedan"; Console.WriteLine(car.model);
C) Car car = new Car(); car.Model("Sedan"); Console.WriteLine(car.Model);
D) Car car = new Car(); car.Model = "Sedan"; Console.WriteLine(car.model);

Answer:
A) Car car = new Car(); car.Model = "Sedan"; Console.WriteLine(car.Model);

4. Scenario: Class Inheritance

Question:
Which code snippet correctly demonstrates inheritance with a Vehicle base class and a Truck derived c

csharp
Copy code
public class Vehicle
{
public void Start() { Console.WriteLine("Vehicle starting"); }
}

public class Truck : Vehicle


{
public void LoadCargo() { Console.WriteLine("Loading cargo"); }
}

// Usage

A) Truck truck = new Truck(); truck.Start(); truck.LoadCargo();


B) Truck truck = new Truck(); truck.LoadCargo(); truck.Start();
C) Vehicle truck = new Truck(); truck.Start(); truck.LoadCargo();
D) Vehicle truck = new Vehicle(); truck.LoadCargo();

Answer:
A) Truck truck = new Truck(); truck.Start(); truck.LoadCargo();

5. Scenario: Method Overloading

Question:
Which code snippet demonstrates method overloading in a Calculator class?

csharp
Copy code
public class Calculator
{
public int Add(int a, int b) { return a + b; }
public double Add(double a, double b) { return a + b; }
}

// Usage

A) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5, 3)); Console.WriteLine(calc.Add(5.0, 3.0));


B) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5)); Console.WriteLine(calc.Add(5.0));
C) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5, 3.0)); Console.WriteLine(calc.Add(5.0, 3));
D) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5, 3)); Console.WriteLine(calc.Add(5, 3));

Answer:
A) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5, 3)); Console.WriteLine(calc.Add(5.0, 3.0));

6. Scenario: Static Methods

Question:
Which code snippet demonstrates the use of a static method GetTotalCount() in a Product class?
csharp
Copy code
public class Product
{
private static int count;

public static int GetTotalCount()


{
return count;
}
}

// Usage

A) Product.GetTotalCount();
B) Product prod = new Product(); prod.GetTotalCount();
C) Product.GetTotalCount(); Product.count = 10;
D) Product.GetTotalCount(); Product.count = Product.count + 1;

Answer:
A) Product.GetTotalCount();

7. Scenario: Object Initialization

Question:
How would you initialize an Employee object with both properties Name and Id using an initializer?

csharp
Copy code
public class Employee
{
public string Name { get; set; }
public int Id { get; set; }
}

// Usage

A) Employee emp = new Employee { Name = "Alice", Id = 123 };


B) Employee emp = new Employee(Name = "Alice", Id = 123);
C) Employee emp = new Employee(); emp.Name = "Alice"; emp.Id = 123;
D) Employee emp = new Employee(); emp.Name = "Alice"; emp.Id = "123";

Answer:
A) Employee emp = new Employee { Name = "Alice", Id = 123 };

8. Scenario: Abstract Classes


Question:
Which code snippet correctly defines an abstract class Shape with an abstract method Draw?

csharp
Copy code
public abstract class Shape
{
public abstract void Draw();
}

public class Circle : Shape


{
public override void Draw()
{
Console.WriteLine("Drawing Circle");
}
}

// Usage

A) Shape shape = new Circle(); shape.Draw();


B) Shape shape = new Shape(); shape.Draw();
C) Circle shape = new Circle(); shape.Draw();
D) Shape shape = new Circle(); shape.Draw();

Answer:
A) Shape shape = new Circle(); shape.Draw();

9. Scenario: Inheritance and Base Class Methods

Question:
Which code snippet demonstrates how a derived class can call a method from its base class?

csharp
Copy code
public class Animal
{
public void Eat()
{
Console.WriteLine("Eating");
}
}

public class Dog : Animal


{
public void Bark()
{
Console.WriteLine("Barking");
}
}

// Usage

A) Dog dog = new Dog(); dog.Eat(); dog.Bark();


B) Dog dog = new Dog(); dog.Bark(); dog.Eat();
C) Animal animal = new Dog(); animal.Bark(); animal.Eat();
D) Animal animal = new Animal(); animal.Bark();

Answer:
A) Dog dog = new Dog(); dog.Eat(); dog.Bark();

10. Scenario: Access Modifiers

Question:
Which code snippet correctly demonstrates the use of protected access modifier in a Person class?

csharp
Copy code
public class Person
{
protected string Name { get; set; }
}

public class Employee : Person


{
public void SetName(string name)
{
Name = name;
}
}

// Usage

A) Employee emp = new Employee(); emp.SetName("John");


B) Person person = new Person(); person.Name = "John";
C) Employee emp = new Employee(); emp.Name = "John";
D) Person person = new Employee(); person.Name = "John";

Answer:
A) Employee emp = new Employee(); emp.SetName("John");

4o mini
Inheritance

1. Scenario: Base and Derived Class

Question:
Which code snippet demonstrates the correct inheritance of a method from a BaseClass to a DerivedCla

csharp
Copy code
public class BaseClass
{
public void Display()
{
Console.WriteLine("BaseClass Display");
}
}

public class DerivedClass : BaseClass


{
}

// Usage

A) DerivedClass obj = new DerivedClass(); obj.Display();


B) BaseClass obj = new DerivedClass(); obj.Display();
C) BaseClass obj = new BaseClass(); obj.Display();
D) DerivedClass obj = new DerivedClass(); obj.Show();

Answer:
A) DerivedClass obj = new DerivedClass(); obj.Display();

2. Scenario: Overriding Methods

Question:
Which code snippet demonstrates overriding a method in a derived class?

csharp
Copy code
public class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal speaks");
}
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}

// Usage

A) Animal a = new Dog(); a.Speak();


B) Dog d = new Animal(); d.Speak();
C) Animal a = new Animal(); a.Speak();
D) Dog d = new Dog(); d.Speak();

Answer:
A) Animal a = new Dog(); a.Speak();

Polymorphism

3. Scenario: Method Overloading

Question:
Which code snippet demonstrates method overloading in a Calculator class?

csharp
Copy code
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}

public double Add(double a, double b)


{
return a + b;
}
}

// Usage

A) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5, 3)); Console.WriteLine(calc.Add(5.0, 3.0));


B) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5, 3)); Console.WriteLine(calc.Add(5, 3.0));
C) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5)); Console.WriteLine(calc.Add(5.0));
D) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5, 3)); Console.WriteLine(calc.Add(5.0, 3));
Answer:
A) Calculator calc = new Calculator(); Console.WriteLine(calc.Add(5, 3)); Console.WriteLine(calc.Add(5.0, 3.0));

4. Scenario: Polymorphic Behavior

Question:
Which code snippet demonstrates polymorphic behavior with an abstract class?

csharp
Copy code
public abstract class Shape
{
public abstract void Draw();
}

public class Circle : Shape


{
public override void Draw()
{
Console.WriteLine("Drawing Circle");
}
}

// Usage

A) Shape shape = new Circle(); shape.Draw();


B) Shape shape = new Shape(); shape.Draw();
C) Circle circle = new Shape(); circle.Draw();
D) Circle circle = new Circle(); circle.Draw();

Answer:
A) Shape shape = new Circle(); shape.Draw();

Interfaces

5. Scenario: Implementing Interfaces

Question:
Which code snippet demonstrates the correct implementation of an interface?

csharp
Copy code
public interface IAnimal
{
void Eat();
}
public class Cat : IAnimal
{
public void Eat()
{
Console.WriteLine("Cat eats");
}
}

// Usage

A) IAnimal animal = new Cat(); animal.Eat();


B) Cat cat = new Cat(); cat.Eat();
C) IAnimal animal = new IAnimal(); animal.Eat();
D) Cat cat = new IAnimal(); cat.Eat();

Answer:
A) IAnimal animal = new Cat(); animal.Eat();

6. Scenario: Multiple Interfaces

Question:
Which code snippet demonstrates a class implementing multiple interfaces?

csharp
Copy code
public interface IWorker
{
void Work();
}

public interface IRest


{
void Rest();
}

public class Employee : IWorker, IRest


{
public void Work()
{
Console.WriteLine("Working");
}

public void Rest()


{
Console.WriteLine("Resting");
}
}
// Usage

A) Employee emp = new Employee(); emp.Work(); emp.Rest();


B) IWorker worker = new Employee(); worker.Work();
C) IRest rest = new Employee(); rest.Rest();
D) Employee emp = new IWorker(); emp.Work(); emp.Rest();

Answer:
A) Employee emp = new Employee(); emp.Work(); emp.Rest();

7. Scenario: Interface with Properties

Question:
Which code snippet demonstrates an interface with a property?

csharp
Copy code
public interface IAccount
{
string AccountNumber { get; set; }
}

public class BankAccount : IAccount


{
public string AccountNumber { get; set; }
}

// Usage

A) BankAccount acc = new BankAccount(); acc.AccountNumber = "12345";


B) IAccount acc = new BankAccount(); acc.AccountNumber = "12345";
C) IAccount acc = new IAccount(); acc.AccountNumber = "12345";
D) BankAccount acc = new IAccount(); acc.AccountNumber = "12345";

Answer:
B) IAccount acc = new BankAccount(); acc.AccountNumber = "12345";

8. Scenario: Explicit Interface Implementation

Question:
Which code snippet demonstrates explicit interface implementation?

csharp
Copy code
public interface IPrinter
{
void Print();
}

public class Document : IPrinter


{
void IPrinter.Print()
{
Console.WriteLine("Printing document");
}
}

// Usage

A) IPrinter printer = new Document(); printer.Print();


B) Document doc = new Document(); doc.Print();
C) Document doc = (IPrinter)new Document(); doc.Print();
D) IPrinter printer = (IPrinter)new Document(); printer.Print();

Answer:
A) IPrinter printer = new Document(); printer.Print();

9. Scenario: Interface Inheritance

Question:
Which code snippet demonstrates an interface inheriting from another interface?

csharp
Copy code
public interface IShape
{
void Draw();
}

public interface IColorable : IShape


{
void Color();
}

public class Circle : IColorable


{
public void Draw()
{
Console.WriteLine("Drawing Circle");
}

public void Color()


{
Console.WriteLine("Coloring Circle");
}
}

// Usage

A) IColorable colorable = new Circle(); colorable.Draw(); colorable.Color();


B) Circle circle = new Circle(); circle.Draw(); circle.Color();
C) IShape shape = new Circle(); shape.Draw();
D) IShape shape = new IColorable(); shape.Draw();

Answer:
A) IColorable colorable = new Circle(); colorable.Draw(); colorable.Color();

10. Scenario: Interface with Methods

Question:
Which code snippet demonstrates an interface with a method that a class implements?

csharp
Copy code
public interface ILogger
{
void Log(string message);
}

public class ConsoleLogger : ILogger


{
public void Log(string message)
{
Console.WriteLine(message);
}
}

// Usage

A) ILogger logger = new ConsoleLogger(); logger.Log("Log message");


B) ConsoleLogger logger = new ConsoleLogger(); logger.Log("Log message");
C) ILogger logger = new ILogger(); logger.Log("Log message");
D) ConsoleLogger logger = new ILogger(); logger.Log("Log message");

Answer:
A) ILogger logger = new ConsoleLogger(); logger.Log("Log message");

Exception Handling
1. Scenario: Handling Divide by Zero Exception

Question:
Which code snippet correctly handles a divide-by-zero exception?

csharp
Copy code
try
{
int numerator = 10;
int denominator = 0;
int result = numerator / denominator;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero.");
}

A) try { /* code */ } catch (DivideByZeroException) { Console.WriteLine("Cannot divide by zero."); }


B) try { /* code */ } catch (Exception ex) { Console.WriteLine("Cannot divide by zero."); }
C) try { /* code */ } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); }
D) try { /* code */ } catch { Console.WriteLine("Cannot divide by zero."); }

Answer:
A) try { /* code */ } catch (DivideByZeroException) { Console.WriteLine("Cannot divide by zero."); }

2. Scenario: Using Finally Block

Question:
Which code snippet demonstrates the use of a finally block to ensure a resource is always closed?

csharp
Copy code
FileStream fileStream = null;
try
{
fileStream = new FileStream("example.txt", FileMode.Open);
// Perform file operations
}
catch (IOException ex)
{
Console.WriteLine("IO Exception occurred.");
}
finally
{
fileStream?.Close();
}
A) try { /* code */ } finally { fileStream.Close(); }
B) try { /* code */ } catch (Exception ex) { /* handle */ } finally { fileStream.Close(); }
C) try { /* code */ } catch (IOException ex) { /* handle */ } finally { fileStream?.Close(); }
D) try { /* code */ } catch (IOException ex) { Console.WriteLine("IO Exception occurred."); }

Answer:
C) try { /* code */ } catch (IOException ex) { /* handle */ } finally { fileStream?.Close(); }

3. Scenario: Custom Exception Handling

Question:
Which code snippet demonstrates the correct way to throw and catch a custom exception?

csharp
Copy code
public class CustomException : Exception
{
public CustomException(string message) : base(message) { }
}

try
{
throw new CustomException("This is a custom exception.");
}
catch (CustomException ex)
{
Console.WriteLine(ex.Message);
}

A) throw new CustomException("message");


B) throw new Exception("This is a custom exception.");
C) throw new CustomException();
D) catch (CustomException ex) { Console.WriteLine(ex.Message); }

Answer:
A) throw new CustomException("message");

File I/O

4. Scenario: Reading from a File

Question:
Which code snippet correctly reads all text from a file?

csharp
Copy code
string path = "example.txt";
string content = File.ReadAllText(path);
Console.WriteLine(content);

A) string content = File.Read(path);


B) string content = File.ReadAllText("example.txt");
C) string content = File.Read("example.txt");
D) string content = File.OpenText("example.txt").ReadToEnd();

Answer:
B) string content = File.ReadAllText("example.txt");

5. Scenario: Writing to a File

Question:
Which code snippet correctly writes a string to a file?

csharp
Copy code
string path = "example.txt";
string content = "Hello, World!";
File.WriteAllText(path, content);

A) File.WriteAllText("example.txt", "Hello, World!");


B) File.Write("example.txt", "Hello, World!");
C) File.AppendAllText("example.txt", "Hello, World!");
D) File.WriteAllText(path, "Hello, World!");

Answer:
A) File.WriteAllText("example.txt", "Hello, World!");

6. Scenario: File Not Found Exception

Question:
Which code snippet correctly handles a file not found exception when trying to read a file?

csharp
Copy code
try
{
string content = File.ReadAllText("nonexistentfile.txt");
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File not found.");
}
A) catch (IOException ex) { Console.WriteLine("File not found."); }
B) catch (FileNotFoundException ex) { Console.WriteLine("File not found."); }
C) catch (Exception ex) { Console.WriteLine("File not found."); }
D) catch { Console.WriteLine("File not found."); }

Answer:
B) catch (FileNotFoundException ex) { Console.WriteLine("File not found."); }

7. Scenario: Appending to a File

Question:
Which code snippet correctly appends a string to an existing file?

csharp
Copy code
string path = "example.txt";
string content = "Appended text.";
File.AppendAllText(path, content);

A) File.WriteAllText(path, content);
B) File.AppendText(path, content);
C) File.AppendAllText(path, content);
D) File.Write(path, content);

Answer:
C) File.AppendAllText(path, content);

8. Scenario: Checking File Existence

Question:
Which code snippet correctly checks if a file exists before attempting to read it?

csharp
Copy code
string path = "example.txt";
if (File.Exists(path))
{
string content = File.ReadAllText(path);
Console.WriteLine(content);
}
else
{
Console.WriteLine("File does not exist.");
}

A) if (File.Exists("example.txt")) { /* read file */ }


B) if (File.ReadAllText("example.txt") != null) { /* read file */ }
C) if (File.Exists(path)) { string content = File.ReadAllText(path); }
D) if (File.Exists(path)) { Console.WriteLine("File exists."); }

Answer:
A) if (File.Exists("example.txt")) { /* read file */ }

9. Scenario: File Stream Usage

Question:
Which code snippet demonstrates how to use FileStream to write bytes to a file?

csharp
Copy code
byte[] bytes = { 0x1, 0x2, 0x3 };
using (FileStream fs = new FileStream("example.bin", FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}

A) using (FileStream fs = new FileStream("example.bin", FileMode.Create)) { fs.Write(bytes); }


B) using (FileStream fs = new FileStream("example.bin", FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); }
C) FileStream fs = new FileStream("example.bin", FileMode.Create); fs.Write(bytes, 0, bytes.Length); fs.Close();
D) using (FileStream fs = new FileStream("example.bin", FileMode.Open)) { fs.Write(bytes, 0, bytes.Length); }

Answer:
B) using (FileStream fs = new FileStream("example.bin", FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); }

10. Scenario: Reading Lines from a File

Question:
Which code snippet correctly reads all lines from a file and prints each line?

csharp
Copy code
string path = "example.txt";
foreach (string line in File.ReadLines(path))
{
Console.WriteLine(line);
}

A) foreach (string line in File.ReadAllLines("example.txt")) { Console.WriteLine(line); }


B) foreach (string line in File.ReadLines(path)) { Console.WriteLine(line); }
C) File.ReadLines(path).ForEach(line => Console.WriteLine(line));
D) File.ReadAllLines(path).ForEach(line => Console.WriteLine(line));

Answer:
B) foreach (string line in File.ReadLines(path)) { Console.WriteLine(line); }
Collections

1. Scenario: Using List<T> for Storage

Question:
Which code snippet correctly demonstrates adding elements to a List<T> and accessing them?

csharp
Copy code
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
Console.WriteLine(names[1]);

A) List<string> names = new List<string>(); names.Add("Alice"); names.Add("Bob"); Console.WriteLine(names


B) List<string> names = new List<string>(); names.AddRange("Alice", "Bob"); Console.WriteLine(names[1]);
C) List<string> names = new List<string>(); names.Insert(0, "Alice"); names.Insert(1, "Bob"); Console.WriteLin
D) List<string> names = new List<string>(); names.Add("Alice"); names.Add("Bob"); Console.WriteLine(names

Answer:
A) List<string> names = new List<string>(); names.Add("Alice"); names.Add("Bob"); Console.WriteLine(names

2. Scenario: Iterating Through a Dictionary

Question:
Which code snippet correctly iterates through a Dictionary<TKey, TValue> and prints each key-value pa

csharp
Copy code
Dictionary<int, string> ages = new Dictionary<int, string>
{
{ 1, "One" },
{ 2, "Two" }
};
foreach (var kvp in ages)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}

A) foreach (KeyValuePair<int, string> kvp in ages) { Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Va
B) foreach (var kvp in ages) { Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); }
C) ages.ForEach(kvp => Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"));
D) foreach (int key in ages.Keys) { Console.WriteLine("Key: " + key + ", Value: " + ages[key]); }

Answer:
B) foreach (var kvp in ages) { Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); }

3. Scenario: Using Stack<T> for LIFO Operations

Question:
Which code snippet demonstrates how to use a Stack<T> to perform push and pop operations?

csharp
Copy code
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
int item = stack.Pop();
Console.WriteLine(item);

A) stack.Push(1); stack.Push(2); int item = stack.Pop(); Console.WriteLine(item);


B) stack.Add(1); stack.Add(2); int item = stack.Remove(); Console.WriteLine(item);
C) stack.Enqueue(1); stack.Enqueue(2); int item = stack.Dequeue(); Console.WriteLine(item);
D) stack.Add(1); stack.Add(2); int item = stack.Extract(); Console.WriteLine(item);

Answer:
A) stack.Push(1); stack.Push(2); int item = stack.Pop(); Console.WriteLine(item);

4. Scenario: Removing Elements from a Queue

Question:
Which code snippet demonstrates how to use a Queue<T> to add and remove elements?

csharp
Copy code
Queue<string> queue = new Queue<string>();
queue.Enqueue("First");
queue.Enqueue("Second");
string item = queue.Dequeue();
Console.WriteLine(item);

A) queue.Enqueue("First"); queue.Enqueue("Second"); string item = queue.Dequeue(); Console.WriteLine(item)


B) queue.Add("First"); queue.Add("Second"); string item = queue.Remove(); Console.WriteLine(item);
C) queue.Add("First"); queue.Add("Second"); string item = queue.Extract(); Console.WriteLine(item);
D) queue.Enqueue("First"); queue.Enqueue("Second"); string item = queue.Extract(); Console.WriteLine(item);

Answer:
A) queue.Enqueue("First"); queue.Enqueue("Second"); string item = queue.Dequeue(); Console.WriteLine(item)

Generics

5. Scenario: Creating a Generic Class


Question:
Which code snippet correctly defines a generic class Box<T> that can store an item of type T?

csharp
Copy code
public class Box<T>
{
private T _item;
public void SetItem(T item)
{
_item = item;
}
public T GetItem()
{
return _item;
}
}

A) public class Box<T> { private T item; public void SetItem(T item) { this.item = item; } public T GetItem() { r
B) public class Box<T> { private T _item; public void SetItem(T item) { _item = item; } public T GetItem() { ret
C) public class Box<T> { private T item; public void Set(T item) { this.item = item; } public T Get() { return item
D) public class Box<T> { private T _item; public void Set(T item) { _item = item; } public T Retrieve() { return

Answer:
B) public class Box<T> { private T _item; public void SetItem(T item) { _item = item; } public T GetItem() { ret

6. Scenario: Using Generic Method

Question:
Which code snippet demonstrates a generic method that swaps two elements in an array?

csharp
Copy code
public void Swap<T>(T[] array, int index1, int index2)
{
T temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}

A) public void Swap<T>(T[] array, int index1, int index2) { T temp = array[index1]; array[index1] = array[index
B) public void Swap<T>(T array, int index1, int index2) { T temp = array[index1]; array[index1] = array[index2
C) public void Swap<T>(T[] array, int index1, int index2) { T temp = array[index1]; array[index2] = array[index
D) public void Swap<T>(T array, int index1, int index2) { T temp = array; array = temp; }

Answer:
A) public void Swap<T>(T[] array, int index1, int index2) { T temp = array[index1]; array[index1] = array[index

7. Scenario: Constraining Generic Type

Question:
Which code snippet demonstrates how to constrain a generic type T to ensure it is a class and has a p

csharp
Copy code
public class Factory<T> where T : class, new()
{
public T Create()
{
return new T();
}
}

A) public class Factory<T> where T : new() { public T Create() { return new T(); } }
B) public class Factory<T> where T : class { public T Create() { return new T(); } }
C) public class Factory<T> where T : class, new() { public T Create() { return new T(); } }
D) public class Factory<T> where T : new() { public T Create() { return Activator.CreateInstance<T>(); } }

Answer:
C) public class Factory<T> where T : class, new() { public T Create() { return new T(); } }

8. Scenario: Generic Interface Implementation

Question:
Which code snippet correctly demonstrates implementing a generic interface IRepository<T>?

csharp
Copy code
public interface IRepository<T>
{
void Add(T item);
T Get(int id);
}

public class Repository<T> : IRepository<T>


{
public void Add(T item) { /* implementation */ }
public T Get(int id) { /* implementation */ return default(T); }
}

A) public class Repository<T> : IRepository<T> { public void Add(T item) { /* implementation */ } public T Get(
B) public class Repository<T> : IRepository<T> { public void Add(T item) { /* implementation */ } public T Get(
C) public class Repository<T> : IRepository<T> { public void Add(T item) { /* implementation */ } public T Get(
D) public class Repository<T> : IRepository<T> { public void Add(T item) { /* implementation */ } public T Get(

Answer:
B) public class Repository<T> : IRepository<T> { public void Add(T item) { /* implementation */ } public T Get(

9. Scenario: Generic Collections with Constraints

Question:
Which code snippet demonstrates the use of a generic list with constraints to ensure type T has a par

csharp
Copy code
public class Container<T> where T : new()
{
public T CreateItem()
{
return new T();
}
}

A) public class Container<T> where T : class { public T CreateItem() { return new T(); } }
B) public class Container<T> where T : new() { public T CreateItem() { return Activator.CreateInstance<T>(); }
C) public class Container<T> where T : new() { public T CreateItem() { return new T(); } }
D) public class Container<T> where T : class, new() { public T CreateItem() { return Activator.CreateInstance<

Answer:
C) public class Container<T> where T : new() { public T CreateItem() { return new T(); } }

10. Scenario: Generic Constraints with Interfaces

Question:
Which code snippet demonstrates a generic class constrained to types implementing a specific interfa

csharp
Copy code
public interface IComparableItem
{
int CompareTo(object obj);
}

public class Comparator<T> where T : IComparableItem


{
public int Compare(T x, T y)
{
return x.CompareTo(y);
}
}
A) public class Comparator<T> where T : IComparableItem { public int Compare(T x, T y) { return x.CompareTo
B) public class Comparator<T> where T : IComparableItem { public int Compare(T x, T y) { return x.Compare(y
C) public class Comparator<T> where T : class, IComparableItem { public int Compare(T x, T y) { return x.Com
D) public class Comparator<T> where T : IComparableItem { public int Compare(T x, T y) { return y.CompareTo

Answer:
A) public class Comparator<T> where T : IComparableItem { public int Compare(T x, T y) { return x.CompareTo

OOP - Inheritance, Polymorphism, Interfaces

1. Scenario: Class Hierarchy Question: You have a base class Vehicle and a derived class Car that
StartEngine using a Vehicle reference pointing to a Car object, what will be the output if the method is c
class's StartEngine method is called.
B) The Car class's StartEngine method is called.
C) A compile-time error occurs.
D) A runtime error occurs.

Answer: B) The Car class's StartEngine method is called.

2. Scenario: Polymorphism with Methods Question: In a system with a base class Employee and
called CalculateSalary, which of the following statements is true when calling CalculateSalary on an Emp
The Employee class's CalculateSalary method is called.
B) The Manager class's CalculateSalary method is called.
C) The program will not compile.
D) The method call will be ambiguous.

Answer: B) The Manager class's CalculateSalary method is called.

3. Scenario: Interface Implementation Question: You have an interface IShape with a method Dra
provide an implementation for Draw, what will happen? A) The class Circle will compile successfully.
B) The class Circle must implement the Draw method to compile.
C) The interface IShape will not be recognized.
D) The class Circle will not compile but can be made abstract.

Answer: B) The class Circle must implement the Draw method to compile.

4. Scenario: Abstract Classes vs. Interfaces Question: When designing a system, you need to d
interface. What is a key reason to choose an interface over an abstract class? A) Interfaces cannot hav
B) Interfaces support multiple inheritance, while abstract classes do not.
C) Abstract classes support multiple inheritance, while interfaces do not.
D) Interfaces can only contain properties, not methods.

Answer: B) Interfaces support multiple inheritance, while abstract classes do not.


5. Scenario: Inheritance Access Modifiers Question: If you declare a method in a base class as p
in a different assembly, what is the result? A) The method can be called directly from the derived clas
B) The method is accessible through the base class only.
C) The method is not accessible from the derived class.
D) The method is accessible if the derived class is marked as internal.

Answer: C) The method is not accessible from the derived class.

6. Scenario: Virtual and Override Methods Question: If a base class method is declared as virtua
keyword, which method will be executed when the method is called on a base class reference holding
will be executed.
B) The derived class method will be executed.
C) The method call will cause a runtime error.
D) The method call will cause a compile-time error.

Answer: B) The derived class method will be executed.

7. Scenario: Multiple Interface Implementation Question: If a class implements multiple interfa


should the class handle this? A) The class must provide a single implementation of the method.
B) The class must implement the method separately for each interface.
C) The compiler will handle the conflict automatically.
D) The class should implement the method with different names for each interface.

Answer: A) The class must provide a single implementation of the method.

Exception Handling and File I/O

8. Scenario: Catching Specific Exceptions Question: You have a try-catch block that catches IOE
FileNotFoundException is thrown, which catch block will handle it? A) The IOException catch block.
B) The FileNotFoundException catch block.
C) Both catch blocks will handle it.
D) None of the catch blocks will handle it.

Answer: B) The FileNotFoundException catch block.

9. Scenario: File Writing with Error Handling Question: In a scenario where you need to write d
in case of an error, which approach is most appropriate? A) Open the file, write data, and close it with
B) Write data in a try block and delete the file in the catch block if an exception occurs.
C) Use a temporary file to write data and rename it to the target file upon successful completion.
D) Use a file stream with Append mode to ensure data integrity.

Answer: C) Use a temporary file to write data and rename it to the target file upon successful comple

10. Scenario: Handling File Not Found Question: If you attempt to open a file for reading and the
you expect to catch? A) FileNotFoundException
B) IOException
C) ArgumentException
D) InvalidOperationException

Answer: A) FileNotFoundException

11. Scenario: Exception Propagation Question: If an exception occurs in a method and is not cau
exception? A) It is ignored by the runtime.
B) It is caught by the nearest catch block in the calling method.
C) It is automatically logged.
D) It causes the application to crash immediately.

Answer: B) It is caught by the nearest catch block in the calling method.

12. Scenario: Exception Handling Best Practices Question: What is considered a best practice w
general Exception type and ignoring the specifics.
B) Using exceptions for control flow within the application.
C) Providing specific catch blocks for different exception types.
D) Catching exceptions at the top-level method only.

Answer: C) Providing specific catch blocks for different exception types.

Collections and Generics

13. Scenario: Choosing Collection Types Question: When should you use a Dictionary<TKey, TValu
maintain the order of elements.
B) When you need to perform frequent lookups by key.
C) When you need to store duplicate elements.
D) When you require a fixed-size collection.

Answer: B) When you need to perform frequent lookups by key.

14. Scenario: Generic Constraints Question: How would you constrain a generic type parameter
constructor in C#? A) where T : struct, new()
B) where T : class, new()
C) where T : new(), struct
D) where T : class

Answer: A) where T : struct, new()

15. Scenario: Collection Performance Question: Which collection type provides O(1) time comple
List<T>
B) Queue<T>
C) HashSet<T>
D) Dictionary<TKey, TValue>

Answer: D) Dictionary<TKey, TValue>


16. Scenario: Generics and Type Safety Question: What is a major advantage of using generics
performance optimization.
B) They provide support for dynamic type resolution at runtime.
C) They eliminate the need for exception handling.
D) They simplify file I/O operations.

Answer: A) They allow for runtime type safety and performance optimization.

17. Scenario: Collection Initialization Question: When initializing a List<T>, which of the followin
a capacity of 0 and grows dynamically.
B) It starts with a capacity of 10 and grows dynamically.
C) It starts with a capacity of 1 and does not grow.
D) It must be explicitly initialized with a specific capacity.

Answer: B) It starts with a capacity of 10 and grows dynamically.

18. Scenario: Collection Type Conversion Question: How can you convert a List<T> to an array i
B) Use the ConvertAll() method.
C) Use the AsEnumerable() method.
D) Use the CopyTo() method.

Answer: A) Use the ToArray() method on the List<T>.

19. Scenario: Generic Methods Question: Which statement is true about generic methods in C#?
B) They can only return objects of the generic type.
C) They can be defined within generic classes or independently.
D) They can only be used with reference types.

Answer: C) They can be defined within generic classes or independently.

20. Scenario: Handling Multiple Data Types Question: If you need a collection that can store mu
and performance, which C# feature is most appropriate? A) ArrayList
B) List<object>
C) Dictionary<string, object>
D) Generics with a constraint

Answer: D) Generics with a constraint

File I/O and Serialization

Task Preview: File I/O

Q1: Consider the following code snippet. What will happen when the Main method is executed?

csharp
Copy code
using System;
using System.IO;

class Program
{
static void Main(string[] args)
{
string path = "example.txt";
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("Hello, World!");
}

using (StreamReader reader = new StreamReader(path))


{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
}

A) The code will not compile due to incorrect file handling.


B) The code will compile but throw a runtime exception when trying to read the file.
C) The code will compile and output "Hello, World!".
D) The code will compile but output nothing because the file is not properly written.

Answer: C

Task Preview: File I/O

Q2: Examine the following code snippet. What will be the output when the Main method is executed?

csharp
Copy code
using System;
using System.IO;

class Program
{
static void Main(string[] args)
{
string path = "log.txt";
if (File.Exists(path))
{
File.Delete(path);
}

File.AppendAllText(path, "Log entry 1\n");


File.AppendAllText(path, "Log entry 2\n");

string content = File.ReadAllText(path);


Console.WriteLine(content);
}
}

A) The code will compile and output "Log entry 1\nLog entry 2".
B) The code will not compile because File.AppendAllText is incorrectly used.
C) The code will compile but throw a runtime exception when trying to delete the file.
D) The code will compile and output "Log entry 1\nLog entry 2\n".

Answer: D

Task Preview: File I/O

Q3: Given the following code, what will happen when the Main method is executed?

csharp
Copy code
using System;
using System.IO;

class Program
{
static void Main(string[] args)
{
string path = "data.txt";

using (FileStream fs = File.Create(path))


{
byte[] info = new System.Text.UTF8Encoding(true).GetBytes("This is some text.");
fs.Write(info, 0, info.Length);
}

using (FileStream fs = File.OpenRead(path))


{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
}
A) The code will not compile due to incorrect usage of FileStream.
B) The code will compile and output "This is some text.".
C) The code will compile but output unreadable characters.
D) The code will compile but throw a runtime exception during file creation.

Answer: B

Task Preview: Serialization

Q4: Consider the following code snippet. What will be the result when the Main method is executed?

csharp
Copy code
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

class Program
{
static void Main(string[] args)
{
Person person = new Person { Name = "John", Age = 30 };
BinaryFormatter formatter = new BinaryFormatter();

using (FileStream fs = new FileStream("person.dat", FileMode.Create))


{
formatter.Serialize(fs, person);
}

using (FileStream fs = new FileStream("person.dat", FileMode.Open))


{
Person deserializedPerson = (Person)formatter.Deserialize(fs);
Console.WriteLine(deserializedPerson.Name + " - " + deserializedPerson.Age);
}
}
}

A) The code will not compile due to serialization issues with the Person class.
B) The code will compile but throw a runtime exception during serialization.
C) The code will compile and output "John - 30".
D) The code will compile but fail to deserialize the Person object correctly.

Answer: C

Scenario 1: Log File Management

Q1: Your application generates a log file every day, recording various events. At the end of each day,
(moved to a backup folder) and a new log file is created for the next day's events. How would you imp

A) Use File.Move() to move the log file to the backup folder and then create a new log file using File.Cre
B) Delete the log file at the end of the day and start writing a new log file immediately.
C) Append all log files into one large file using File.AppendAllText().
D) Overwrite the existing log file with new entries every day.

Answer: A

Scenario 2: Reading Large Files

Q2: You are tasked with reading a large text file (over 2 GB) containing millions of lines. The file need
should minimize memory usage to avoid crashing. Which approach should you take?

A) Use File.ReadAllLines() to read the entire file into a string array and then process each line.
B) Use File.ReadLines() to read the file line by line in a memory-efficient manner.
C) Use StreamReader.ReadToEnd() to load the entire file content into a single string.
D) Use FileStream and manually manage reading bytes from the file.

Answer: B

Scenario 3: Serialization of Complex Objects

Q3: You need to serialize a complex object graph that includes circular references (where an object re
the first object). What should you do to ensure successful serialization and deserialization?

A) Use the BinaryFormatter and set the PreserveObjectReferences property to true.


B) Implement the ISerializable interface and manually handle the serialization process.
C) Use the JsonSerializer with ReferenceLoopHandling set to Ignore.
D) Break the circular references before serialization and restore them after deserialization.

Answer: B
Scenario 4: Secure Data Serialization

Q4: Your application needs to serialize sensitive user data (such as passwords) to a file. To maintain s
serialization and decrypted during deserialization. What approach should you take?

A) Use a BinaryFormatter to serialize the object, then encrypt the resulting file using a symmetric encry
B) Serialize the object as plain text and rely on file system permissions to protect the data.
C) Serialize the object using XmlSerializer and use an XSLT transformation to secure the XML file.
D) Use a custom Stream class that encrypts data during serialization and decrypts during deserializatio

Answer: A

Scenario 5: Handling Serialization Exceptions

Q5: During the deserialization process of a previously serialized object, an exception is thrown indicat
object was serialized. How should you handle this scenario?

A) Implement a versioning system in your serialized objects and handle different versions during dese
B) Always deserialize objects using the same class version, ensuring no changes in the class structure
C) Ignore the exception and continue processing the rest of the data.
D) Modify the serialized file manually to match the new object structure.

Answer: A
nted accurately.

ding errors?

at runtime?
application lifecycle.

s its properties.
Problem Statement: Contact Information Storage System

You are tasked with developing a Contact Information Storage System using .NET. This system should

Requirements

1. Class Definition: Implement a class named ContactStorage with methods to handle serialization

2. Data Structure: Define a Contact class with the following properties:

Id: A unique identifier for the contact (string).


Name: The name of the contact (string).
PhoneNumber: The phone number of the contact (string).
Email: The email address of the contact (string).

The Contact class should be marked as [Serializable] to allow for binary serialization.

3. Methods: Implement the ContactStorage class with the following methods:

SaveContactsToFile(List<Contact> contacts, string filePath):

Description: Serializes the list of Contact objects and writes it to the specified file.
Parameters:
contacts: The list of Contact objects to be serialized.
filePath: The path to the file where the serialized data will be saved.
Returns: void
Exceptions:
IOException: If an error occurs while writing to the file.
SerializationException: If the object cannot be serialized.

LoadContactsFromFile(string filePath):

Description: Reads and deserializes a list of Contact objects from the specified file.
Parameters:
filePath: The path to the file from which the data will be read.
Returns: A List<Contact> containing the deserialized contact information.
Exceptions:
IOException: If an error occurs while reading from the file.
SerializationException: If the data in the file cannot be deserialized.
FileNotFoundException: If the file does not exist.

4. Serialization Format:
Use the BinaryFormatter class for serialization and deserialization.

5. Edge Cases:

Ensure that the methods handle cases where the file does not exist or is not accessible.
Handle scenarios where the file contents do not match the expected format.
rializing and deserializing contact data to and from files.

anage saving and loading contact information from files.


Task Program: Library Management System with File I/O and Serializati

Introduction

This project extends the basic implementation of a Library Management System by incorporating file I
of books and members. The system should manage books and members using serialization to save an

Task

You need to implement the following methods in LibraryService.cs and handle file I/O for persisting the

1. AddBook Method

The LibraryService.AddBook method is called when a librarian adds a new book to the library's collection

Create a new Book object.


Add it to the Books list.
Ensure that no duplicate ISBNs exist in the collection.

A book can only be added if the following requirements are met:

The ISBN consists of exactly 13 characters and contains only numbers.


The title contains at least 1 character.
The author contains at least 1 character.
The book is not already present in the collection (based on ISBN).

If any parameter is incorrect, the method should throw an ArgumentException.

2. SearchBooks Method

The LibraryService.SearchBooks method is called when a user searches for books in the library's collecti

isbn: The book's ISBN. It can be null or empty if the user does not want to filter on ISBN.
title: The book's title. It can be null or empty if the user does not want to filter on title.
author: The book's author. It can be null or empty if the user does not want to filter on author.

The method should return a list of books that match the search criteria. Matching against the title and

An empty list should be returned if the user does not set any of the search parameters (i.e., all param
match the search criteria.

3. Serialization and File I/O


SaveLibraryDataToFile: Implement a method to serialize and save the list of books to a file. This m
changes are made to the book collection, such as after adding a new book.

LoadLibraryDataFromFile: Implement a method to deserialize and load the list of books from a file.
application starts to restore the book collection from persistent storage.

Constraints

Use only the provided Book class.


Ensure the AddBook method handles duplicate ISBNs appropriately.
Ensure the SearchBooks method handles null or empty search parameters correctly.
Ensure file operations are robust and handle potential errors gracefully.
Ensure serialization and deserialization handle various cases, including missing or corrupted files.

Notes

You may create additional helper methods if necessary.


Focus on writing clean and readable code.
Ensure proper exception handling as per the problem statement.
Problem Statement: Employee Management System with File I/O and Serialization

Introduction

This project extends the basic Employee Management System by incorporating file I/O and serializatio
persistent storage of employees and departments. The system should use serialization to save and lo
employee and department data to and from files, ensuring that the data is preserved between session

Task

You need to implement the following functionalities in the EmployeeService class, with an emphasis on
serialization:

1. AddEmployee Method

The EmployeeService.AddEmployee method is called when an HR manager adds a new employee to the
This method should:

Create a new Employee object.


Add it to the Employees list.
Ensure that no duplicate employee IDs exist in the system.

An employee can only be added if the following requirements are met:

The EmployeeID is a non-empty string and is unique.


The Name contains at least 1 character.
The DepartmentID is a non-empty string and matches an existing department's ID in the Departments li

If any parameter is incorrect, the method should throw an ArgumentException.

Additionally, after adding an employee, the employee data should be serialized and saved to a file to
persistent storage.

2. GetEmployeesByDepartment Method

The EmployeeService.GetEmployeesByDepartment method is called when an HR manager wants to retriev


employees in a specific department. The method parameters are:

departmentID: The ID of the department for which employees are to be retrieved. It cannot be null or e

The method should return a list of employees who belong to the specified department.

An empty list should be returned if the departmentID does not match any department in the Departmen
there are no employees in the specified department.
Additionally, the method should ensure that the retrieved employee data is up-to-date by loading the
data from the file before performing the search.

3. Serialization and File I/O

SaveEmployeeDataToFile: Implement a method to serialize and save the list of employees and dep
to a file. This method should be called whenever changes are made to the employee or department co
such as after adding a new employee.

LoadEmployeeDataFromFile: Implement a method to deserialize and load the list of employees an


departments from a file. This method should be called when the application starts to restore the empl
department data from persistent storage.

Constraints

Use only the provided Employee and Department classes.


Ensure the AddEmployee method handles duplicate employee IDs appropriately.
Ensure the GetEmployeesByDepartment method handles invalid department IDs correctly.
Ensure file operations are robust and handle potential errors gracefully.
Ensure serialization and deserialization handle various cases, including missing or corrupted files.

Notes

You may create additional helper methods if necessary.


Focus on writing clean and readable code.
Ensure proper exception handling as per the problem statement.
Problem Statement: Finding Concatenated Word Sequences with File I/

You are given a string s and an array of strings words, where all the strings in words are of the same le
defined as a string that exactly matches the concatenation of any permutation of the strings in words.

For instance, if words = ["ab", "cd", "ef"], the following are valid concatenated strings: "abcdef", "abefcd
"efcdab". However, "acdbef" is not valid because it does not match any permutation of the concatena

Your task is to return an array of starting indices where these concatenated substrings occur within s.
does not matter.

You need to implement the following functionalities in the StringMatcher class, with an emphasis on file

1. FindConcatenatedSequences Method

The StringMatcher.FindConcatenatedSequences method is called to identify starting indices where the co


given string s. The method parameters are:

s: The string in which to search for concatenated word sequences.


words: An array of strings where all strings are of the same length. These strings form the concatenate

The method should return an array of starting indices where these concatenated substrings occur with
output does not matter.

Ensure that the method handles edge cases such as empty strings and lists properly, and the implem
large input sizes.

Examples

1. Example 1:

Input: s = "barfoothefoobarman", words = ["foo", "bar"]


Output: [0, 9]
Explanation:
The substring starting at index 0 is "barfoo", which is a valid permutation of ["bar", "foo"].
The substring starting at index 9 is "foobar", which is also a valid permutation of ["foo", "bar"].

2. Example 2:

Input: s = "wordgoodgoodgoodbestword", words = ["word", "good", "best", "word"]


Output: []
Explanation: There are no substrings in s that match the concatenation of any permutation of words.

3. Example 3:
Input: s = "barfoofoobarthefoobarman", words = ["bar", "foo", "the"]
Output: [6, 9, 12]
Explanation:
The substring starting at index 6 is "foobarthe", which is a valid permutation of ["foo", "bar", "the"].
The substring starting at index 9 is "barthefoo", which is a valid permutation of ["bar", "the", "foo"].
The substring starting at index 12 is "thefoobar", which is a valid permutation of ["the", "foo", "bar"].

2. SaveWordListToFile Method

Implement a method to serialize and save the array of words (words) to a file. This method should be c
updated or changed.

3. LoadWordListFromFile Method

Implement a method to deserialize and load the array of words from a file. This method should be call
class to restore the word list from persistent storage.

4. IsConcatenatedString Method

The StringMatcher.IsConcatenatedString method is called to check if a given string s can be formed by co


any permutation. The parameters are:

s: The string to be checked.


words: An array of strings where all strings are of the same length.

The method should return true if s can be formed by concatenating the words in the list in any permut

Constraints

Ensure that the FindConcatenatedSequences method handles large input sizes efficiently.
Use only the provided StringMatcher class.
Ensure that file operations for saving and loading the word list handle potential errors gracefully.
Ensure proper serialization and deserialization of the word list.
Handle edge cases such as empty strings and lists in all methods.

Notes

You may create additional helper methods if necessary.


Focus on writing clean, efficient, and readable code.
Ensure proper exception handling and validation as per the problem statement.

You might also like