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 compile code into machine language
B. To query data using a consistent syntax
C. To manage operating system files
D. To create graphical user interfaces

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

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

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

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

4 What does the OrderBy() LINQ method do?

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

5 What is a delegate in C#?

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

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

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

7 What does an interface primarily define in C#?

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

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

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

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

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

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

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

11 Which keyword marks a C# method as asynchronous?

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

12 What does the await keyword do?

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

13 What does the Single Responsibility Principle state?

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

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 extension, closed for modification
D. Open for testing, closed for inheritance

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

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

17 What does the Interface Segregation Principle encourage?

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

18 Which situation violates ISP?

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

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. Comments
B. Loops
C. Namespaces
D. Interfaces

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. 2, 5, 8, 11, 14
B. 1, 4, 7
C. 1, 4, 7, 5, 7
D. 2, 8, 14

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.FirstOrDefault(e => e.Salary > 60000)?.Name
B. employees.Single(e => e.Salary > 60000).Name
C. employees.First(e => e.Salary > 60000).Name
D. employees.Where(e => e.Salary > 60000).First().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 query uses deferred execution until it is enumerated
B. The Where method copies the list asynchronously
C. The compiler postpones execution because Price is private
D. LINQ queries always execute only inside a loop

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

LINQ to Collections Medium
A. Join(o => o.CustomerId)
B. GroupBy(o => o.CustomerId)
C. Select(o => o.CustomerId)
D. OrderBy(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 automatically run handlers on background threads
B. The publisher controls when the event is raised
C. Subscribers can invoke the event from any class
D. Events remove the need for delegate instances

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

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

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

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

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

Generics in C# Medium
A. It prevents all runtime exceptions
B. It provides compile-time type safety and avoids unnecessary boxing
C. It allows integers and unrelated objects in one strongly typed list
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 be an interface
B. T must inherit from object directly
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. IEnumerable<string> can be assigned to IEnumerable<object>
B. Action<object> can never be assigned to Action<string>
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 blocks every thread in the application
B. It creates a new operating-system process
C. It converts the task result into a synchronous loop
D. It pauses the method without blocking the calling thread

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. await Task.Run(() => GetAAsync()); await Task.Run(() => GetBAsync());
C. Task.WaitAll(GetAAsync(), 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 forces the method to return a value of type void
C. It can block the UI thread and contribute to deadlocks
D. It changes every exception into a compiler warning

35 Which design most closely follows the Single Responsibility Principle?

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

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. Open/Closed Principle
B. Single Responsibility Principle
C. Liskov Substitution Principle
D. Interface Segregation 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. Split the large interface into smaller role-specific interfaces
B. Add empty method bodies to the unused members
C. Make all interface members static
D. Move every member into the report model class

39 Which design best demonstrates the Dependency Inversion Principle?

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

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

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

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> automatically batches network requests
C. IQueryable<T> represents an expression tree for provider translation
D. IEnumerable<T> can translate expressions into SQL

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.FirstOrDefault(x => x > 2, -1)
C. values.First(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. Add Distinct before GroupBy
B. Replace GroupBy with ToLookup
C. Use ThenByDescending inside the grouping key
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 remove the need to handle subscriber exceptions
B. Events prevent subscribers from invoking the delegate directly
C. Events automatically execute callbacks on background threads
D. Events guarantee that callbacks run in subscription order

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. Use DynamicInvoke for every subscriber
D. Copy the delegate reference before invoking it

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. Mark one interface method as new in the class
B. Declare one public Reset method only
C. Use explicit interface implementations for both members
D. Rename one interface member in the class

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. Add a default interface implementation
B. Replace all methods with static methods
C. Make every existing implementation partial
D. Change the interface into a sealed class

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

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

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 classes with public constructors
C. It permits T to contain arbitrary reference fields
D. It restricts T to types without managed references

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 returned values are automatically combined
B. The two operations can overlap in execution
C. The two operations always run on separate threads
D. The second operation cannot observe exceptions

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 compiler removes the awaited continuation
C. The UI context converts exceptions into cancellations
D. The continuation waits for a context blocked by .Result

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

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

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. Create focused services for querying, formatting, storage, email, and auditing
B. Create a subclass for every report format
C. Add more private methods to ReportService
D. Move all methods into a static utility class

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. Create an IPaymentProcessor strategy for each payment type
B. Add a default branch to the existing switch
C. Duplicate the method for every payment type
D. Make the switch expression public

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 base type violates dependency inversion
D. The subtype strengthens the input precondition

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

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

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. Split the interface into smaller capability interfaces
B. Keep the interface and throw for unsupported members
C. Make all members static extension methods
D. Use one abstract base class with empty methods

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

Dependency Inversion Principle (DIP) Hard
A. Move both concrete types into the service namespace
B. Wrap construction in a larger static method
C. Inject abstractions implemented by the repository and sender
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. The interface can no longer be mocked
B. Singletons cannot implement interfaces
C. Request data may leak across concurrent consumers
D. The container will always create duplicate instances