Unit 3: Advanced C# Programming - Practice Quiz

CSE253 — .Net Programming 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is the main purpose of LINQ in C#?

Language Integrated Query (LINQ) Easy
A. To manage operating system files
B. To create graphical user interfaces
C. To compile code into machine language
D. To query data using a consistent syntax

2 Which LINQ method is commonly used to filter a collection?

Language Integrated Query (LINQ) Easy
A. Count()
B. Select()
C. Where()
D. OrderBy()

3 Which LINQ method is used to project each element of a collection into a new form?

LINQ to Collections Easy
A. First()
B. Where()
C. Any()
D. Select()

4 What does the OrderBy() LINQ method do?

LINQ to Collections Easy
A. Removes duplicate elements
B. Counts all elements
C. Joins two collections
D. Sorts elements in ascending order

5 What is a delegate in C#?

Delegates and Events Easy
A. A block of comments
B. A container for constants
C. A type of database table
D. A reference to a method

6 What is an event commonly used for in C#?

Delegates and Events Easy
A. Converting strings to numbers
B. Creating a new namespace
C. Notifying objects about an action
D. Storing data in an array

7 What does an interface primarily define in C#?

Interfaces Easy
A. A private memory location
B. A contract for implementing types
C. A collection of database records
D. A complete executable program

8 Which keyword is used when a class implements an interface?

Interfaces Easy
A. inherits
B. extends
C. uses
D. implements

9 What is a main benefit of generics in C#?

Generics in C# Easy
A. They automatically create user interfaces
B. They remove the need for classes
C. They provide type-safe reusable code
D. They prevent all runtime exceptions

10 Which notation is used to specify a generic type parameter?

Generics in C# Easy
A. Parentheses ()
B. Square brackets []
C. Angle brackets <>
D. Curly braces {}

11 Which keyword marks a C# method as asynchronous?

Asynchronous Programming using Async and Await Easy
A. defer
B. await
C. parallel
D. async

12 What does the await keyword do?

Asynchronous Programming using Async and Await Easy
A. Converts a method into a delegate
B. Waits for an asynchronous operation
C. Creates a new class
D. Stops the application permanently

13 What does the Single Responsibility Principle state?

Single Responsibility Principle (SRP) Easy
A. A class must contain one method
B. A class should have one reason to change
C. A project should have one class
D. A program should use one variable

14 Which design best follows SRP?

Single Responsibility Principle (SRP) Easy
A. One class handles reports and database storage
B. One method manages all program features
C. One class handles reports and another stores them
D. One class handles every application task

15 What does the Open/Closed Principle recommend?

Open/Closed Principle (OCP) Easy
A. Open for deletion, closed for execution
B. Open for editing, closed for compilation
C. Open for testing, closed for inheritance
D. Open for extension, closed for modification

16 What is the main idea of the Liskov Substitution Principle?

Liskov Substitution Principle (LSP) Easy
A. Methods should never accept parameters
B. Classes should avoid using inheritance
C. Base classes should replace all interfaces
D. Subtypes should replace base types safely

17 What does the Interface Segregation Principle encourage?

Interface Segregation Principle (ISP) Easy
A. One large interface for every class
B. Interfaces with no members
C. Private interfaces only
D. Small, focused interfaces

18 Which situation violates ISP?

Interface Segregation Principle (ISP) Easy
A. A class implements a focused interface
B. A class provides all members it needs
C. A class uses two small interfaces
D. A class depends on methods it never uses

19 What does the Dependency Inversion Principle suggest?

Dependency Inversion Principle (DIP) Easy
A. Depend on abstractions, not concrete classes
B. Place all code in one class
C. Avoid using interfaces in applications
D. Depend only on global variables

20 Which C# feature is commonly used to support dependency inversion?

Dependency Inversion Principle (DIP) Easy
A. Namespaces
B. Comments
C. Interfaces
D. Loops

21 What is the result of the following LINQ query?

CSHARP
var numbers = new[] { 2, 5, 8, 11, 14 };
var result = numbers.Where(n => n % 2 == 0).Select(n => n / 2);



Which values are produced when result is enumerated?

Language Integrated Query (LINQ) Medium
A. 1, 4, 7, 5, 7
B. 2, 8, 14
C. 2, 5, 8, 11, 14
D. 1, 4, 7

22 Given the collection below, which LINQ expression returns the name of the first employee whose salary is greater than 60000, or null if no employee matches?

CSHARP
List<Employee> employees;

LINQ to Collections Medium
A. employees.Where(e => e.Salary > 60000).First().Name
B. employees.First(e => e.Salary > 60000).Name
C. employees.FirstOrDefault(e => e.Salary > 60000)?.Name
D. employees.Single(e => e.Salary > 60000).Name

23 Why does the following query not immediately execute against the list?

CSHARP
var query = products.Where(p => p.Price > 100);

Language Integrated Query (LINQ) Medium
A. The compiler postpones execution because Price is private
B. The query uses deferred execution until it is enumerated
C. LINQ queries always execute only inside a loop
D. The Where method copies the list asynchronously

24 Which LINQ operation is most appropriate for grouping orders by their customer identifier?

LINQ to Collections Medium
A. Join(o => o.CustomerId)
B. OrderBy(o => o.CustomerId)
C. GroupBy(o => o.CustomerId)
D. Select(o => o.CustomerId)

25 A class publishes an event named DataReceived. Which declaration best follows the standard .NET event pattern?

Delegates and Events Medium
A. public Func<DataReceivedEventArgs> DataReceived;
B. public event EventHandler<DataReceivedEventArgs> DataReceived;
C. public delegate void DataReceived();
D. public event Action DataReceived;

26 What is a key benefit of using an event instead of exposing a delegate field publicly?

Delegates and Events Medium
A. Events remove the need for delegate instances
B. Events automatically run handlers on background threads
C. The publisher controls when the event is raised
D. Subscribers can invoke the event from any class

27 A class implements IComparable<Product>. Which method must it provide?

Interfaces Medium
A. void CompareTo(object value)
B. bool Compare(Product other)
C. int CompareTo(Product? other)
D. Product CompareWith(Product other)

28 What does interface-based programming primarily allow in a C# application?

Interfaces Medium
A. Every interface member automatically receives a default implementation
B. Interfaces guarantee that all implementations use identical algorithms
C. Code can depend on a contract rather than a concrete implementation
D. A class can inherit implementation from multiple classes

29 Why is List<int> generally preferable to ArrayList when storing integers?

Generics in C# Medium
A. It allows integers and unrelated objects in one strongly typed list
B. It prevents all runtime exceptions
C. It provides compile-time type safety and avoids unnecessary boxing
D. It automatically sorts every inserted integer

30 What is the purpose of the generic constraint in this declaration?

CSHARP
static T Create<T>() where T : new()

Generics in C# Medium
A. T must inherit from object directly
B. T must be an interface
C. T must be a nullable value type
D. T must contain a public parameterless constructor

31 Which statement about generic variance is correct for reference types?

Generics in C# Medium
A. Action<object> can never be assigned to Action<string>
B. IEnumerable<string> can be assigned to IEnumerable<object>
C. Dictionary<string, int> can be assigned to Dictionary<object, int>
D. List<string> can be assigned to List<object>

32 What is the main effect of applying await to an incomplete task in an asynchronous method?

Asynchronous Programming using Async and Await Medium
A. It pauses the method without blocking the calling thread
B. It converts the task result into a synchronous loop
C. It creates a new operating-system process
D. It blocks every thread in the application

33 Which code efficiently starts two independent asynchronous operations and waits for both to finish?

Asynchronous Programming using Async and Await Medium
A. var a = await GetAAsync(); var b = await GetBAsync();
B. Task.WaitAll(GetAAsync(), GetBAsync());
C. await Task.Run(() => GetAAsync()); await Task.Run(() => GetBAsync());
D. var a = GetAAsync(); var b = GetBAsync(); await Task.WhenAll(a, b);

34 Why is calling .Result on an asynchronous operation discouraged in UI applications?

Asynchronous Programming using Async and Await Medium
A. It always cancels the operation
B. It can block the UI thread and contribute to deadlocks
C. It changes every exception into a compiler warning
D. It forces the method to return a value of type void

35 Which design most closely follows the Single Responsibility Principle?

Single Responsibility Principle (SRP) Medium
A. One class validates orders, saves them, and sends notifications
B. One class exposes every operation required by the entire application
C. One class handles order validation while separate classes handle persistence and notifications
D. One class stores data and directly controls database connections and user interfaces

36 A billing system uses a separate IPricingRule implementation for each discount type. New discount types can be added without modifying the billing service. Which principle does this design demonstrate?

Open/Closed Principle (OCP) Medium
A. Interface Segregation Principle
B. Open/Closed Principle
C. Single Responsibility Principle
D. Liskov Substitution Principle

37 Which situation is a likely violation of the Liskov Substitution Principle?

Liskov Substitution Principle (LSP) Medium
A. A derived class uses a private helper method to simplify inherited behavior
B. A derived class adds a method that is not present in the base class
C. A derived class overrides a virtual method with a faster implementation
D. A derived class throws NotSupportedException for a behavior promised by its base type

38 A ReadOnlyReportViewer is forced to implement Print, Export, and Edit methods even though it only displays reports. What refactoring best applies ISP?

Interface Segregation Principle (ISP) Medium
A. Add empty method bodies to the unused members
B. Move every member into the report model class
C. Make all interface members static
D. Split the large interface into smaller role-specific interfaces

39 Which design best demonstrates the Dependency Inversion Principle?

Dependency Inversion Principle (DIP) Medium
A. A repository depends on a user-interface control for connection settings
B. A service directly creates a SqlRepository inside its constructor
C. A service uses static methods so no dependencies appear in its signature
D. A service depends on IRepository and receives an implementation through dependency injection

40 What is a practical testing benefit of injecting an interface-based dependency into a class?

Dependency Inversion Principle (DIP) Medium
A. The injected dependency can never throw an exception
B. All classes using the interface become immutable
C. The compiler automatically verifies the business requirements
D. A test double can replace the real dependency during testing

41 Given IEnumerable<int> source = new[] { 1, 2, 3, 4 }; var query = source.Where(x => x % 2 == 0); source = new[] { 5, 6, 7, 8 }; var result = query.ToArray(); What is the value of result?

Language Integrated Query (LINQ) Hard
A. { 2, 4 }
B. An exception is thrown because source was reassigned
C. { 2, 4, 6, 8 }
D. { 6, 8 }

42 Which statement best explains why IQueryable<T> queries can behave differently from IEnumerable<T> queries when the source is a remote provider?

Language Integrated Query (LINQ) Hard
A. IQueryable<T> always executes immediately
B. IEnumerable<T> can translate expressions into SQL
C. IEnumerable<T> automatically batches network requests
D. IQueryable<T> represents an expression tree for provider translation

43 For var values = new[] { 1, 2, 2, 3, 4 };, which expression returns the first element greater than 2, or -1 when no such element exists, without throwing for an empty match?

LINQ to Collections Hard
A. values.SingleOrDefault(x => x > 2, -1)
B. values.First(x => x > 2, -1)
C. values.FirstOrDefault(x => x > 2, -1)
D. values.DefaultIfEmpty(-1).First(x => x > 2)

44 Consider var query = items.GroupBy(x => x.Category).Select(g => new { g.Key, Count = g.Count() });. Which change is required to guarantee that categories are processed in descending order of their counts?

LINQ to Collections Hard
A. Use ThenByDescending inside the grouping key
B. Replace GroupBy with ToLookup
C. Add Distinct before GroupBy
D. Add OrderByDescending(x => x.Count) after Select

45 Why should a class normally expose an event instead of exposing a public delegate field for notification callbacks?

Delegates and Events Hard
A. Events automatically execute callbacks on background threads
B. Events prevent subscribers from invoking the delegate directly
C. Events guarantee that callbacks run in subscription order
D. Events remove the need to handle subscriber exceptions

46 A publisher raises an event while one subscriber unsubscribes itself during event handling. What is the most reliable way to ensure the current notification uses a stable handler list?

Delegates and Events Hard
A. Invoke the event directly several times
B. Clear the event before invoking each handler
C. Copy the delegate reference before invoking it
D. Use DynamicInvoke for every subscriber

47 A class implements two interfaces that both define a parameterless method named Reset, but the methods require different behavior. Which implementation resolves the collision while preserving both contracts?

Interfaces Hard
A. Declare one public Reset method only
B. Mark one interface method as new in the class
C. Rename one interface member in the class
D. Use explicit interface implementations for both members

48 An interface evolves by adding a new abstract member. Existing third-party implementations immediately fail to compile. Which design change most directly reduces this versioning problem in modern C#?

Interfaces Hard
A. Replace all methods with static methods
B. Add a default interface implementation
C. Change the interface into a sealed class
D. Make every existing implementation partial

49 Which statement about generic variance is correct for reference types?

Generics in C# Hard
A. List<string> can be assigned to List<object>
B. IEnumerable<string> can be assigned to IEnumerable<object>
C. Func<object> can be assigned to Func<string>
D. Action<object> can be assigned to Action<string>

50 What is the primary purpose of the constraint where T : unmanaged on a generic type parameter?

Generics in C# Hard
A. It forces T to implement IComparable<T>
B. It restricts T to types without managed references
C. It permits T to contain arbitrary reference fields
D. It restricts T to classes with public constructors

51 A method starts Task<int> a = GetValueAsync(); Task<int> b = GetValueAsync(); and then awaits both tasks. Compared with awaiting the first call before starting the second, what is the main behavioral difference?

Asynchronous Programming using Async and Await Hard
A. The second operation cannot observe exceptions
B. The returned values are automatically combined
C. The two operations always run on separate threads
D. The two operations can overlap in execution

52 Why can calling .Result on an incomplete task inside a UI synchronization context cause a deadlock?

Asynchronous Programming using Async and Await Hard
A. The task loses its result after suspension
B. The continuation waits for a context blocked by .Result
C. The UI context converts exceptions into cancellations
D. The compiler removes the awaited continuation

53 Which implementation correctly preserves cancellation semantics for an asynchronous operation that supports a CancellationToken?

Asynchronous Programming using Async and Await Hard
A. Ignore the token until the operation has completed
B. Catch OperationCanceledException and always return success
C. Pass the token to the operation and allow cancellation to propagate
D. Convert every cancellation request into TimeoutException

54 A ReportService queries sales data, formats HTML, writes files, sends email, and records audit entries. Which refactoring best applies SRP?

Single Responsibility Principle (SRP) Hard
A. Move all methods into a static utility class
B. Add more private methods to ReportService
C. Create focused services for querying, formatting, storage, email, and auditing
D. Create a subclass for every report format

55 A billing method contains a growing switch over payment types, requiring edits whenever a new payment type is introduced. Which design most directly supports OCP?

Open/Closed Principle (OCP) Hard
A. Duplicate the method for every payment type
B. Create an IPaymentProcessor strategy for each payment type
C. Make the switch expression public
D. Add a default branch to the existing switch

56 A subtype overrides Save and rejects inputs that the base type accepts, even though callers rely on the base contract. Which principle violation is most directly present?

Liskov Substitution Principle (LSP) Hard
A. The caller violates interface segregation
B. The subtype weakens the input precondition
C. The subtype strengthens the input precondition
D. The base type violates dependency inversion

57 A ReadOnlyFile derives from File, but inherits Write and throws NotSupportedException. What is the strongest design correction?

Liskov Substitution Principle (LSP) Hard
A. Suppress the exception in ReadOnlyFile
B. Make Write virtual with an empty default body
C. Separate readable and writable abstractions
D. Add a Boolean flag controlling whether writes succeed

58 A Printer interface requires Print, Scan, Fax, and Staple, causing simple printers to implement unused members. Which change best follows ISP?

Interface Segregation Principle (ISP) Hard
A. Use one abstract base class with empty methods
B. Split the interface into smaller capability interfaces
C. Make all members static extension methods
D. Keep the interface and throw for unsupported members

59 A high-level OrderService directly constructs SqlOrderRepository and SmtpEmailSender. Which change most directly applies DIP?

Dependency Inversion Principle (DIP) Hard
A. Inject abstractions implemented by the repository and sender
B. Wrap construction in a larger static method
C. Move both concrete types into the service namespace
D. Make the concrete types inherit from OrderService

60 A dependency injection composition root registers IClock with a singleton implementation that stores mutable request-specific state. What is the principal design risk?

Dependency Inversion Principle (DIP) Hard
A. Singletons cannot implement interfaces
B. Request data may leak across concurrent consumers
C. The interface can no longer be mocked
D. The container will always create duplicate instances