CSharp QA
C# QA:
1. Which of the following C# features allows you to
define immutable data types with value-based equality?
a) Pattern Matching
b) Record Types
c) Nullable Reference Types
d) Async/Await
Answer: b) Record Types
Explanation: The correct answer is b) Record Types. Record types in C# allow you to define immutable data types with value-based equality, where equality is determined by property values. Other options (Pattern Matching, Nullable Reference Types, and Async/Await) do not focus on immutability or value-based equality.
2. What is the purpose of nullable reference types in C#
8.0 and later?
a) To make all reference types non-nullable by default
b) To ensure that reference types can never be null
c) To allow reference types to have nullable values with explicit null checks
d) To enable value types to be nullable
Answer: c) To allow reference types to have nullable
values with explicit null checks
Explanation: The correct answer is c) To allow reference types to have nullable values with explicit null checks. Nullable reference types, introduced in C# 8.0, let reference types be nullable (e.g., string?
) and enforce explicit null checks to avoid null reference exceptions. This improves null safety in the code.
3. In C#, which operator is used to perform a
"switch-like" comparison with multiple patterns in a pattern matching
expression?
a) =>
b) match
c) is
d) ??
Answer: c) is
Explanation: The correct answer is c) is. In C#, the is
operator is used for pattern matching to perform "switch-like" comparisons with multiple patterns, checking types or matching values. Other options, like =>
, match
, and ??
, are unrelated to pattern matching.
4. What does the async keyword in C# signify?
a) The method will run synchronously
b) The method contains asynchronous code that will be executed in parallel
c) The method will return a Task or Task<T>
d) The method is automatically executed in a background thread
Answer: c) The method will return a Task or Task<T>
Explanation: The correct answer is c) The method will return a Task or Task<T>. The async
keyword in C# signifies that the method contains asynchronous code and will return a Task
or Task<T>
. It enables the use of await
within the method, allowing asynchronous operations without blocking the main thread.
5. Which of the following features allows C# developers
to perform parallel processing on collections using LINQ?
a) Task.Run
b) Parallel LINQ (PLINQ)
c) async/await
d) Parallel.ForEach
Answer: b) Parallel LINQ (PLINQ)
Explanation: PLINQ allows C# developers to perform parallel processing on collections using LINQ by utilizing multiple processor cores. It enables efficient, parallelized queries for CPU-bound tasks.
6. Which of the following allows you to write code that
runs concurrently in a non-blocking manner in C#?
a) Task Parallel Library (TPL)
b) Pattern Matching
c) Nullable Reference Types
d) Record Types
Answer: a) Task Parallel Library (TPL)
Explanation: TPL in C# allows developers to write concurrent, non-blocking code by managing tasks and parallel operations. It simplifies asynchronous and parallel programming, enabling efficient execution of multiple tasks.
7. Which of the following enhancements in C# 9.0 enables
the creation of data objects that are both immutable and have built-in
value-based equality comparison?
a) Nullable Reference Types
b) Record Types
c) Async/Await
d) LINQ Enhancements
Answer: b) Record Types
Explanation: C# 9.0 introduced record types, which allow the creation of immutable data objects with built-in value-based equality. This means instances of record types are compared based on their values, not their references.
8. What feature was introduced in C# 9.0 to make
reference types behave as nullable by default and to improve null safety?
a) Nullable Reference Types
b) Value Tuple Types
c) Record Types
d) Pattern Matching
Answer: a) Nullable Reference Types
Explanation: Introduced in C# 8.0 and improved in C# 9.0, this feature makes reference types nullable by default and enhances null safety. It enables the compiler to detect potential null reference issues and enforce explicit null checks.
9. Which of the following C# features allows a method to
wait for asynchronous operations without blocking the thread?
a) Parallel.ForEach
b) async/await
c) Record Types
d) Pattern Matching
Answer: b) async/await
Explanation: The async/await
keywords in C# allow methods to wait for asynchronous operations without blocking the thread. This improves performance by enabling non-blocking, asynchronous execution of code.
10. In C#, what does the Task Parallel Library (TPL)
provide?
a) A way to work with async methods
b) A set of methods to perform parallel operations on tasks
c) An easy way to define immutable data objects
d) A mechanism for pattern matching in data types
Answer: b) A set of methods to perform parallel
operations on tasks
Explanation: The Task Parallel Library (TPL) in C# provides methods like Task.Run
and Parallel.ForEach
to execute operations concurrently, improving performance for CPU-bound tasks. It simplifies writing parallel and asynchronous code for better efficiency.
11. Which of the following is the correct syntax to
define a record type in C# 9.0?
a) public record Person { string Name; int Age; }
b) public class Person { string Name; int Age; }
c) public record Person(string Name, int Age);
d) public record Person { string Name, int Age; }
Answer: c) public record Person(string Name, int
Age);
Explanation: In C# 9.0, record types are defined using a concise syntax that includes the properties in the constructor, making them immutable by default. This syntax automatically generates the necessary properties and provides value-based equality.
12. What does the is keyword enable in C# pattern
matching?
a) Defining conditional logic for nullable types
b) Checking if an object is of a specific type and optionally extracting it
c) Defining asynchronous code blocks
d) Comparing value types for equality
Answer: b) Checking if an object is of a specific
type and optionally extracting it
Explanation: The is
keyword in C# pattern matching allows you to check if an object is of a particular type and, if so, cast it to that type in a concise manner. This enables more readable and safe type checking and extraction in code.
13. Which of the following keywords is used to define a
method that will return a Task and can be awaited in C#?
a) async
b) await
c) Task
d) parallel
Answer: a) async
Explanation: The async
keyword is used to define a method in C# that will return a Task
(or Task<T>
) and can be awaited. This allows the method to perform asynchronous operations without blocking the thread.
14. What feature does C# 8.0 introduce to improve the
safety of reference types by indicating whether they can be null or not?
a) Pattern Matching
b) Record Types
c) Nullable Reference Types
d) Parallel Programming
Answer: c) Nullable Reference Types
Explanation: C# 8.0 introduced nullable reference types, which help improve null safety by allowing developers to specify whether reference types can be null. This feature enables the compiler to detect potential null reference errors and enforce explicit null checks.
15. Which of the following does the await keyword do in
an asynchronous method?
a) Immediately executes the code asynchronously without
blocking
b) Waits for a Task to complete and returns the result
c) Forces a method to run synchronously
d) Prevents parallel execution of the code
Answer: b) Waits for a Task to complete and returns
the result
Explanation: The await
keyword in C# is used within an asynchronous method to pause execution until the awaited Task
is complete, and then returns the result. It allows non-blocking execution while waiting for asynchronous operations to finish.
16. Which of the following is a key benefit of using the
Task Parallel Library (TPL) in C#?
a) It simplifies the syntax of LINQ queries.
b) It provides a way to work with collections concurrently.
c) It guarantees that tasks will run sequentially.
d) It reduces memory consumption in multi-threaded applications.
Answer: b) It provides a way to work with collections
concurrently.
Explanation: The Task Parallel Library (TPL) in C# enables parallel processing, allowing collections and operations to be handled concurrently, improving performance for CPU-bound tasks. It simplifies parallel programming by handling task management and synchronization automatically.
17. What does the Task.WhenAll() method do in C#
asynchronous programming?
a) Waits for all tasks to complete and then returns the
results as a list
b) Cancels all running tasks
c) Executes the tasks sequentially
d) Splits the tasks into separate threads for parallel execution
Answer: a) Waits for all tasks to complete and then
returns the results as a list
Explanation: The Task.WhenAll()
method in C# waits for all provided tasks to finish and then returns a Task
that represents the completion of all tasks. If the tasks return values, it provides the results as an array.
18. Which of the following C# features is used to
simplify working with asynchronous programming by providing a more readable
syntax?
a) async/await
b) Task.Run
c) Parallel.ForEach
d) PLINQ
Answer: a) async/await
Explanation: The async/await
keywords in C# simplify asynchronous programming by allowing developers to write asynchronous code in a more readable, synchronous-like style. This approach avoids callback hell and makes handling asynchronous operations easier and more intuitive.
19. Which C# feature enables pattern matching on types
and values, such as matching on primitive types, ranges, or even complex
objects?
a) LINQ
b) Record Types
c) Pattern Matching
d) Nullable Reference Types
Answer: c) Pattern Matching
Explanation: C# pattern matching allows you to match types and values, including primitive types, ranges, and complex objects. This feature simplifies conditional logic and enhances code readability by enabling more expressive and concise patterns for comparisons.
20. In C# 9.0, which of the following are the key
benefits of using record types over classes?
a) Record types are immutable by default and support
value-based equality.
b) Record types can only be used for numeric data types.
c) Record types are reference types, but with mutable properties.
d) Record types cannot be inherited.
Answer: a) Record types are immutable by default and
support value-based equality.
Explanation: In C# 9.0, record types are designed to be immutable by default, meaning their properties cannot be modified after initialization. Additionally, they support value-based equality, meaning two record instances are considered equal if their property values are the same.
21. Which of the following C# features allows a developer
to perform parallel processing with better performance by managing tasks more
efficiently?
a) LINQ
b) Async/Await
c) Parallel LINQ (PLINQ)
d) Pattern Matching
Answer: c) Parallel LINQ (PLINQ)
Explanation: PLINQ extends LINQ to support parallel processing, improving performance by running queries concurrently on multiple processor cores. It efficiently manages tasks and parallelizes operations on collections, making it ideal for CPU-bound tasks.
22. In C# 9.0, how do you define an init-only property in
a record type?
a) public string Name { get; set; }
b) public string Name { get; init; }
c) public init string Name;
d) public string Name => set;
Answer: b) public string Name { get; init; }
Explanation: In C# 9.0, init-only
properties are defined using the init
accessor, allowing the property to be set only during object initialization. This ensures immutability after the object is created, which is common in record types.
23. Which of the following is a feature of the async
method in C#?
a) It automatically runs in a background thread
b) It cannot return any values
c) It can only execute synchronous code
d) It returns a Task or Task<T>
Answer: d) It returns a Task or Task<T>
Explanation: In C#, an async
method must return a Task
(for methods with no return value) or Task<T>
(for methods that return a value). This allows the method to be awaited, enabling asynchronous execution without blocking the thread.
24. Which of the following methods can be used to perform
parallel iteration over a collection in C#?
a) Parallel.For
b) Task.WhenAll
c) Parallel LINQ (PLINQ)
d) async/await
Answer: a) Parallel.For
Explanation: The Parallel.For
method in C# allows for parallel iteration over a collection, executing iterations concurrently on multiple threads for improved performance. It is typically used for CPU-bound tasks that can be parallelized.
25. What feature introduced in C# 9.0 allows for
non-nullable reference types to be explicitly checked for null?
a) Pattern Matching
b) Record Types
c) Nullable Reference Types
d) Async/Await
Answer: c) Nullable Reference Types
Explanation: Introduced in C# 8.0 and enhanced in C# 9.0, nullable reference types allow developers to explicitly declare whether a reference type can be null. This feature helps the compiler catch potential null reference errors, improving code safety.
26. Which of the following C# constructs allows
developers to create a new object based on an existing object with modified
properties, typically used in record types?
a) Object initializer
b) With-expression
c) Null-coalescing operator
d) LINQ Select method
Answer: b) With-expression
Explanation: In C# 9.0, the with
expression allows developers to create a new object based on an existing one, while modifying specific properties. This is especially useful in record types, which are immutable by default.
27. Which of the following correctly defines an async
method that performs an HTTP request and returns a Task<string>?
a) public async Task<string> GetData() { return await
HttpClient.GetStringAsync("url"); }
b) public async Task GetData() { return
HttpClient.GetStringAsync("url"); }
c) public async string GetData() { return await
HttpClient.GetStringAsync("url"); }
d) public Task<string> GetData() { return
HttpClient.GetStringAsync("url"); }
Answer: a) public async Task<string> GetData()
{ return await HttpClient.GetStringAsync("url"); }
Explanation: This method is asynchronous (async
), returns a Task<string>
, and uses await
to asynchronously perform the HTTP request with HttpClient.GetStringAsync("url")
. The await
keyword ensures the method doesn't block while waiting for the HTTP request to complete.
28. Which of the following is a key advantage of using Parallel.ForEach
in C# for parallel processing?
a) It provides better syntax for iterating over collections.
b) It automatically handles asynchronous operations.
c) It divides the work into multiple threads for concurrent execution,
improving performance.
d) It allows for the creation of immutable data types.
Answer: c) It divides the work into multiple threads
for concurrent execution, improving performance.
Explanation: Parallel.ForEach
in C# splits the collection into smaller tasks, which are processed concurrently across multiple threads, improving performance for CPU-bound tasks. This is especially beneficial when performing intensive operations on large collections.
29. Which of the following is a valid use of the is
keyword in C# pattern matching?
a) if (x is int {0}) { }
b) if (x is not null) { }
c) if (x is string > 5) { }
d) if (x is int n and > 5) { }
Answer: b) if (x is not null) { }
Explanation: The is
keyword in C# can be used in pattern matching to check if an object is not null, simplifying null checks. This pattern is introduced in C# 9.0, making the code more readable and concise.
30. In C# 9.0, which of the following features allows you
to define a type that is automatically initialized with default values?
a) Record types with init properties
b) Value tuples
c) Nullable reference types
d) The default keyword in constructors
Answer: a) Record types with init properties
Explanation: In C# 9.0, record types allow you to define immutable objects with init
-only properties, which can be initialized during object creation. These properties automatically get default values if not explicitly assigned, making initialization straightforward and consistent.
31. In C# 9.0, what is the purpose of the with
expression?
a) To update a class instance with a new value
b) To create a new instance of an object based on an existing one, with some
properties modified
c) To mark a method as async
d) To define a property in a class as nullable
Answer: b) To create a new instance of an object
based on an existing one, with some properties modified
Explanation: In C# 9.0, the with
expression allows creating a new instance of a record type, copying the values from an existing object while modifying specified properties. This is useful for immutability, as it enables creating modified copies without changing the original object.
32. Which of the following is true about C#'s nullable
reference types?
a) They allow the compiler to automatically convert all
reference types to non-nullable types.
b) They help reduce null reference exceptions by making nullability explicit.
c) They make value types nullable by default.
d) They are enabled by default in all C# projects.
Answer: b) They help reduce null reference exceptions
by making nullability explicit.
Explanation: Nullable reference types, introduced in C# 8.0, allow developers to explicitly specify whether a reference type can be null, helping the compiler detect potential null reference errors. This improves code safety and reduces runtime exceptions.
33. What does the following pattern matching expression
do in C#: if (x is int { } y)?
a) It checks if x is an int and assigns it to variable y if
the condition is true.
b) It checks if x is an integer that is not null and extracts its value into y.
c) It checks if x is a non-null integer and matches any value of y.
d) It will always match, regardless of x's type.
Answer: a) It checks if x is an int and assigns it to
variable y if the condition is true.
Explanation: In this pattern matching expression, x is int { } y
checks if x
is of type int
and, if so, assigns it to the variable y
. This syntax allows for both type checking and variable assignment in a single expression.
34. What is the difference between Task.WhenAny() and Task.WhenAll()
in asynchronous programming in C#?
a) Task.WhenAll() waits for any task to complete, while Task.WhenAny()
waits for all tasks to complete.
b) Task.WhenAll() returns the first completed task, while Task.WhenAny()
returns all tasks' results.
c) Task.WhenAll() waits for all tasks to complete, while Task.WhenAny() waits
for the first task to complete.
d) Task.WhenAll() cancels all tasks once any task completes, while Task.WhenAny()
waits for all tasks to finish.
Answer: c) Task.WhenAll() waits for all tasks to
complete, while Task.WhenAny() waits for the first task to complete.
Explanation: Task.WhenAll()
waits for all the tasks in a collection to complete and returns when they all finish. In contrast, Task.WhenAny()
returns as soon as any single task completes, providing the first finished task.
35. Which of the following C# features allows you to
define a class with a custom equality logic based on its properties?
a) Records
b) Pattern Matching
c) Nullable Reference Types
d) Task Parallel Library
Answer: a) Records
Explanation: In C# 9.0, records provide built-in support for value-based equality, meaning instances of a record type are considered equal if their properties have the same values. This custom equality logic is automatically generated for records, making them ideal for immutable data types that require equality comparison based on properties.
36. What is the purpose of the default keyword in C# when
used with nullable types?
a) It converts a value type to a nullable reference type.
b) It provides a default value for nullable value types.
c) It forces a variable to be null.
d) It initializes all reference types as nullable.
Answer: b) It provides a default value for nullable
value types.
Explanation: In C#, the default
keyword, when used with nullable value types (e.g., int?
), returns the default value of the underlying type, which is null
. This allows you to initialize nullable types without explicitly assigning a value.
37. Which C# feature allows for defining multiple catch
blocks with different conditions?
a) Exception filtering with when keyword
b) Record types
c) Asynchronous exception handling
d) Pattern matching in exception handling
Answer: a) Exception filtering with when keyword
Explanation: In C#, you can use the when
keyword in a catch
block to define conditions under which a specific exception type is handled. This allows for more precise exception handling by applying filters to the exceptions based on additional conditions.
38. Which of the following does the Task.Run() method in
C# allow?
a) It runs a synchronous task in the background.
b) It executes a method asynchronously by placing it in a background thread.
c) It defines an asynchronous method to execute parallel tasks.
d) It waits for a task to complete without blocking the thread.
Answer: b) It executes a method asynchronously by
placing it in a background thread.
Explanation: Task.Run()
in C# is used to run a method asynchronously, offloading the task to a separate thread. This is useful for executing CPU-bound operations in the background without blocking the main thread.
39. Which of the following is true about C#'s init
property setter?
a) It can be set only in a constructor or at the point of
object initialization.
b) It allows modification at any point in the code.
c) It is similar to a regular set but also makes the property read-only after
initialization.
d) It is used for reference types only.
Answer: a) It can be set only in a constructor or at
the point of object initialization.
Explanation: The init
property setter in C# allows the property to be set only during object initialization or in the constructor, making it immutable after the object is fully initialized. This ensures the property cannot be modified later, promoting immutability.
40. Which C# feature allows you to match a range of
values, like matching integers within a specific range or conditions, in
pattern matching?
a) Type patterns
b) Positional patterns
c) Relational patterns
d) Constant patterns
Answer: c) Relational patterns
Explanation: Introduced in C# 9.0, relational patterns allow you to match values based on conditions such as ranges, e.g., checking if a number is within a specific range. They enable more flexible and expressive pattern matching for comparing values with relational operators like <
, >
, <=
, and >=
.
41. Which of the following is true about C#'s record
types in comparison to class types?
a) record types support reference equality only.
b) record types provide value-based equality and are immutable by default.
c) record types support inheritance like class types.
d) record types are always mutable.
Answer: b) record types provide value-based equality
and are immutable by default.
Explanation: In C#, record types are designed for scenarios where you need immutability and value-based equality, meaning two records with the same data are considered equal. Unlike class types, record types cannot be modified after initialization, ensuring their properties remain constant.
42. Which of the following keywords enables better null
safety by making reference types non-nullable by default in C# 8.0 and later?
a) init
b) nullable
c) nullability
d) nullable reference types
Answer: d) nullable reference types
Explanation: Introduced in C# 8.0, nullable reference types make reference types non-nullable by default, helping to catch potential null reference errors at compile time. This feature improves code safety by allowing developers to explicitly define whether a reference type can be null.
43. What does the async modifier in C# indicate?
a) The method will execute synchronously on a separate
thread.
b) The method returns a Task or Task<T> and can contain await
expressions.
c) The method will block the calling thread until execution is completed.
d) The method can only be executed with the await keyword.
Answer: b) The method returns a Task or Task<T>
and can contain await expressions.
Explanation: The async
modifier in C# marks a method as asynchronous, meaning it returns a Task
or Task<T>
, and allows the use of the await
keyword to pause execution until the awaited task completes without blocking the thread.
44. Which of the following statements is true about the
C# await keyword?
a) It executes an asynchronous operation synchronously.
b) It must be used with a method marked as async and waits for the result of a Task.
c) It blocks the calling thread to wait for the task to complete.
d) It is used to terminate an asynchronous operation immediately.
Answer: b) It must be used with a method marked as async
and waits for the result of a Task.
Explanation: The await
keyword in C# is used inside an async
method to pause execution until a Task
completes, allowing the method to run asynchronously without blocking the calling thread. It doesn't block the thread but asynchronously waits for the result.
45. What is the output of the following C# code?
int? x = null;
Console.WriteLine(x ?? 5);
a) null
b) x
c) 5
d) Compilation error
Answer: c) 5
Explanation: The ??
operator is the null-coalescing operator, which returns the value on the right-hand side if the left-hand side is null
. In this case, since x
is null
, it returns 5
, which is the value specified after the ??
.
46. Which of the following features introduced in C# 9.0
allows you to initialize read-only properties in a constructor or an object
initializer?
a) readonly
b) init
c) const
d) set
Answer: b) init
Explanation: In C# 9.0, the init
keyword allows properties to be initialized only during object creation, either in the constructor or through object initialization. Unlike readonly
, init
enables immutability after the object is fully initialized, making properties effectively read-only after initialization.
47. Which C# feature allows you to create a shallow copy
of an object and modify only certain properties using a concise syntax in C#
9.0?
a) Pattern matching
b) with expression
c) init keyword
d) async methods
Answer: b) with expression
Explanation: In C# 9.0, the with
expression allows you to create a shallow copy of an object and modify only certain properties. This is commonly used with record types, providing a concise and immutable way to update specific fields while keeping the rest of the object unchanged.
48. Which of the following does the Task.WhenAll() method
do in C#?
a) Waits for the first task to complete and returns the
result.
b) Waits for all tasks to complete and returns an array of their results.
c) Executes tasks in parallel and returns the results as a list.
d) Cancels all tasks once the first one completes.
Answer: b) Waits for all tasks to complete and
returns an array of their results.
Explanation: The Task.WhenAll()
method in C# is used to wait for a collection of tasks to complete. Once all tasks finish, it returns an array of their results, enabling efficient handling of multiple asynchronous operations simultaneously.
49. Which C# feature allows you to perform null checks in
patterns and extract values from objects in a concise way?
a) is pattern matching
b) default keyword
c) init properties
d) async/await
Answer: a) is pattern matching
Explanation: In C#, is
pattern matching allows you to check an object's type and, if the check is successful, extract its value in a concise manner. This feature can also be used for null checks and value extraction in a single expression, improving code readability and safety.
50. What is the purpose of the Parallel.ForEach() method
in C#?
a) It processes collections in parallel, executing each
iteration on a separate thread.
b) It executes the method in parallel, synchronizing threads to complete
faster.
c) It runs asynchronous tasks in sequence.
d) It splits the data into chunks for optimized processing in a linear manner.
Answer: a) It processes collections in parallel,
executing each iteration on a separate thread.
Explanation: The Parallel.ForEach()
method in C# allows for concurrent processing of each item in a collection. It splits the work across multiple threads, improving performance for large collections by utilizing available CPU cores efficiently.
51. What is the default behavior of reference types in C#
when nullable reference types are enabled?
a) They are always assumed to be non-nullable.
b) They are considered nullable unless explicitly marked as non-nullable.
c) They are assumed to be non-nullable unless the reference is assigned null.
d) They must always be initialized in the constructor.
Answer: b) They are considered nullable unless
explicitly marked as non-nullable.
Explanation: When nullable reference types are enabled in C# (introduced in C# 8.0), reference types are assumed to be nullable by default. To make them non-nullable, you must explicitly add the #nullable enable
directive and mark reference types with ?
(e.g., string?
).
52. Which C# feature introduced in C# 9.0 enables the
creation of deeply immutable types with value-based equality comparisons?
a) readonly properties
b) init properties
c) Record types
d) Pattern matching
Answer: c) Record types
Explanation: Introduced in C# 9.0, record types provide a way to define immutable types with value-based equality comparisons. They automatically generate methods like Equals()
and GetHashCode()
based on the values of their properties, making them ideal for situations where immutability and equality comparisons based on data are needed.
53. Which of the following is a valid C# pattern match?
if (obj is int x)
a) This matches if obj is of type int and assigns its value
to x.
b) This throws an exception if obj is of type int.
c) This only matches obj if x is greater than 10.
d) This checks if x is null.
Answer: a) This matches if obj is of type int and
assigns its value to x.
Explanation: In C#, the is
keyword with a pattern matching expression checks if the object obj
is of a specific type (in this case, int
) and, if it is, assigns the value to the variable x
. This is a concise way to perform both type checking and variable extraction in one step.
54. What does the Task.WhenAny() method in C# return?
a) It returns the results of all tasks once they are
completed.
b) It returns the first task that completes.
c) It cancels all tasks and returns null.
d) It waits for all tasks to complete and returns the result of the first
completed task.
Answer: b) It returns the first task that completes.
Explanation: The Task.WhenAny()
method in C# waits for the first task to complete from a collection of tasks and returns that task. It does not wait for all tasks to complete like Task.WhenAll()
. The result is the first completed task, not the final outcome of all tasks.
55. Which of the following is a key feature of nullable
reference types in C# 8.0 and later?
a) They provide a way to eliminate all null reference
exceptions in the code.
b) They allow nullable value types to be used with reference types.
c) They help enforce null-safety by indicating if a reference type can be null.
d) They automatically convert all reference types to nullable.
Answer: c) They help enforce null-safety by
indicating if a reference type can be null.
Explanation: In C# 8.0 and later, nullable reference types allow developers to explicitly mark reference types as nullable or non-nullable. This helps enforce null-safety and reduce the risk of null reference exceptions by making the nullability of references explicit during compile-time.
56. Which of the following C# keywords is used to define
a method that will always return a value, even if it's an empty task?
a) void
b) Task
c) async
d) Task<T>
Answer: b) Task
Explanation: In C#, the Task
keyword is used to define a method that performs an asynchronous operation but does not return any value. It represents an ongoing operation, but unlike void
, it allows for better task tracking and error handling. If the method does not return a value, Task
is used instead of Task<T>
.
57. What does the Parallel LINQ (PLINQ) allow you to do
in C#?
a) Perform parallel iterations on data while maintaining the
order of results.
b) Perform parallel query operations over collections.
c) Convert LINQ queries into asynchronous operations.
d) Execute LINQ queries over multiple threads sequentially.
Answer: b) Perform parallel query operations over
collections.
Explanation: Parallel LINQ (PLINQ) in C# allows you to execute LINQ queries in parallel, distributing the work across multiple threads. This improves performance when working with large datasets by utilizing multiple CPU cores. PLINQ handles parallel execution automatically and can also optimize queries for better efficiency.
58. Which C# keyword is used to define an object property
that can be assigned only during object initialization or within a constructor?
a) readonly
b) init
c) const
d) set
Answer: b) init
Explanation: The init
keyword in C# defines a property that can only be set during object initialization or within a constructor. It provides a way to create immutable properties after the object is constructed, making the property read-only after initialization, which enhances immutability. This was introduced in C# 9.0.
59. Which of the following is true regarding C#'s Task
Parallel Library (TPL)?
a) It is designed to simplify parallel and asynchronous
programming using async and await.
b) It can only be used for running LINQ queries concurrently.
c) It uses the Task class to manage asynchronous operations on a single thread.
d) It provides classes for parallel loops and concurrent data structures.
Answer: d) It provides classes for parallel loops and
concurrent data structures.
Explanation: The Task Parallel Library (TPL) in C# simplifies parallel and asynchronous programming by providing classes like Task
, Parallel
, and ConcurrentQueue
, which help manage parallel operations, such as executing loops concurrently and safely handling shared data structures in a multithreaded environment.
60. Which of the following features introduced in C# 9.0
makes it easier to define and work with immutable data types?
a) Pattern Matching
b) Record Types
c) Nullable Reference Types
d) Parallel LINQ
Answer: b) Record Types
Explanation: In C# 9.0, record types provide a concise way to define immutable data types. They automatically generate methods for value-based equality comparisons, and their properties are immutable by default, making them ideal for representing data that should not change after creation.
a) Task represents a single asynchronous operation.
b) Task is used to represent multiple asynchronous operations at once.
c) Task is used only for handling parallel tasks, not async methods.
d) Task is used to manage synchronous operations.
Answer: a) Task represents a single asynchronous
operation.
Explanation: In C#, a Task represents an asynchronous operation that can be awaited, allowing the program to continue executing other code while waiting for the task to complete. It is commonly used to manage asynchronous methods that return no value, and its generic counterpart, Task, is used for asynchronous operations that return a result.
62. In C# 9.0, which of the following allows you to make
a class immutable and have value-based equality comparisons automatically
generated?
a) readonly properties
b) init properties
c) record types
d) sealed classes
Answer: c) record types
Explanation: In C# 9.0, record types are introduced to automatically create immutable classes with value-based equality. This means that instances of a record are immutable by default, and the system automatically generates methods like Equals()
and GetHashCode()
, which compare the values of the properties rather than their references. This feature is especially useful for working with data objects.
63. Which of the following C# features allows you to
create a variable that may or may not hold a null value for reference types?
a) Nullable reference types
b) Nullable value types
c) Default value types
d) Value tuples
Answer: a) Nullable reference types
Explanation: In C# 8.0 and later, nullable reference types allow developers to specify whether a reference type can hold a null
value. By enabling this feature, reference types can be explicitly declared as nullable or non-nullable, helping to reduce the occurrence of null reference exceptions and improving code safety.
64. Which C# method allows you to run multiple tasks in
parallel and wait for all of them to complete?
a) Task.WhenAll()
b) Task.WhenAny()
c) Task.Run()
d) Task.WaitAll()
Answer: a) Task.WhenAll()
Explanation: Task.WhenAll() allows you to run multiple asynchronous tasks in parallel and waits for all of them to complete. It returns a single task that completes when all of the provided tasks have finished, and it can also aggregate results if the tasks return values.
65. Which of the following C# features was introduced in
C# 7.0 to simplify working with tuples and improve readability?
a) Named tuples
b) Record types
c) Pattern matching
d) Async streams
Answer: a) Named tuples
Explanation: In C# 7.0, named tuples were introduced to improve readability and make working with tuples easier. By giving names to the elements of a tuple, developers can reference them more clearly, improving code clarity and maintenance. For example: (int x, int y) = (1, 2);
.
66. Which C# method allows you to execute asynchronous
methods concurrently and returns the first task to complete?
a) Task.WhenAll()
b) Task.WhenAny()
c) Task.Run()
d) Task.WaitAll()
Answer: b) Task.WhenAny()
Explanation: The Task.WhenAny()
method allows you to execute multiple asynchronous tasks concurrently and returns the first task that completes. It does not wait for all tasks to finish, but instead, it provides the result of the first completed task.
67. Which C# feature, introduced in C# 9.0, provides an
easy way to create new immutable objects based on an existing one while
changing certain properties?
a) with expression
b) readonly keyword
c) default keyword
d) async methods
Answer: a) with expression
Explanation: In C# 9.0, the with
expression allows you to create a new instance of an immutable record type based on an existing object, modifying specific properties. This simplifies the process of updating an object's state without modifying the original object, making it ideal for working with immutable data structures.
68. Which of the following C# features allows you to
define a class with a constructor that initializes properties, while also using
an expression-bodied member?
a) init properties
b) readonly fields
c) async properties
d) Expression-bodied constructors
Answer: d) Expression-bodied constructors
Explanation: Expression-bodied constructors in C# allow you to define a constructor using a concise syntax, where the body consists of a single expression. This feature simplifies the code for initializing properties or fields when the constructor logic is simple and doesn't require multiple statements.
69. Which of the following is true regarding asynchronous
streams introduced in C# 8.0?
a) They allow asynchronous iteration over a collection of
data using await foreach.
b) They are used for defining value-based equality comparisons in records.
c) They allow parallel tasks to be processed synchronously.
d) They are used to implement async-await operations in LINQ.
Answer: a) They allow asynchronous iteration over a
collection of data using await foreach.
Explanation: Asynchronous streams in C# 8.0 enable the use of await foreach
to iterate over data that is produced asynchronously, such as data retrieved from an external source like a file or a network request. This allows non-blocking, asynchronous iteration over collections.
70. Which of the following C# features helps reduce null
reference exceptions by making it explicit whether a reference type can be
null?
a) Records
b) nullable reference types
c) init properties
d) Pattern matching
Answer: b) nullable reference types
Explanation: Nullable reference types, introduced in C# 8.0, help reduce null reference exceptions by explicitly indicating whether a reference type can be null. When enabled, it distinguishes between nullable and non-nullable reference types, making the nullability of reference types explicit and preventing unintended null dereferencing.
71. Which of the following is used to define properties
in C# that are only assignable at the time of object initialization?
a) readonly
b) init
c) set
d) get
Answer: b) init
Explanation: In C#, the init
keyword is used to define properties that can only be assigned during object initialization or within a constructor. This allows for immutability after the object has been initialized, making the property effectively read-only after construction.
72. Which of the following statements about pattern
matching in C# is true?
a) Pattern matching allows type-based comparisons only.
b) Pattern matching provides a concise way to work with types and values, such
as switch expressions.
c) Pattern matching only works with simple types like integers.
d) Pattern matching is only applicable to value types.
Answer: b) Pattern matching provides a concise way to
work with types and values, such as switch expressions.
Explanation: Pattern matching in C# allows developers to match both types and values concisely, making code more readable and efficient. It can be used in various scenarios, including switch
expressions, type checks, and even more complex patterns like relational and positional matching.
73. Which C# feature allows the use of async streams to
read and process data asynchronously?
a) Task.WhenAny()
b) await foreach
c) Task.WhenAll()
d) Parallel.ForEach()
Answer: b) await foreach
Explanation: In C#, await foreach
allows you to asynchronously iterate over a stream of data provided by an async enumerable. This feature, introduced in C# 8.0, enables processing of data asynchronously as it becomes available, without blocking the calling thread. It is particularly useful for scenarios like reading data from an I/O-bound source, such as files or network streams.
74. What is the output of the following C# code snippet?
int? x = null;
Console.WriteLine(x ??= 10);
a) null
b) x
c) 10
d) Compilation error
Answer: c) 10
Explanation: Explanation:
The null-coalescing assignment operator (??=
) checks if the left-hand operand (x
) is null. Since x
is initially null
, the operator assigns 10
to x
and returns the value. Therefore, the output of Console.WriteLine(x ??= 10);
is 10
, and x
is now assigned the value 10
.
75. In C# 8.0, which of the following is the correct
syntax to enable nullable reference types for a project?
a) #nullable enable
b) nullable enable
c) #enable nullable
d) null enable
Answer: a) #nullable enable
Explanation: In C# 8.0, the #nullable enable
directive is used to enable nullable reference types for the project. This ensures that reference types are checked for nullability, helping prevent null reference exceptions.
76. What is the key benefit of using async and await in
C# for I/O-bound operations?
a) It makes operations faster by executing them on a
different thread.
b) It allows the program to continue execution without blocking the calling
thread while waiting for an I/O task to complete.
c) It forces the method to execute synchronously.
d) It enables multi-threading to run multiple tasks in parallel.
Answer: b) It allows the program to continue
execution without blocking the calling thread while waiting for an I/O task to
complete.
Explanation: The async
and await
keywords in C# allow asynchronous execution, enabling the calling thread to continue executing other tasks while waiting for I/O-bound operations (like file or network I/O) to complete, without blocking the thread. This improves efficiency and responsiveness in applications.
77. Which of the following methods is used to create and
run asynchronous tasks in parallel in C#?
a) Task.Run()
b) Parallel.ForEach()
c) Task.WhenAny()
d) Task.WhenAll()
Answer: a) Task.Run()
Explanation: Task.Run()
is used to create and execute an asynchronous task on a separate thread, allowing the task to run in parallel. This method helps in offloading work from the main thread to improve performance, especially for I/O-bound or computationally intensive operations.
78. Which C# keyword allows you to define an
expression-bodied method or property?
a) =>
b) async
c) readonly
d) init
Answer: a) =>
Explanation: The =>
keyword is used in C# to define expression-bodied methods or properties. It allows for concise syntax, enabling a method or property to return a value directly in a single expression without needing a full method body. This is commonly used for methods that return a simple result.
79. Which of the following allows you to assign a default
value to a nullable value type in C#?
a) ?? operator
b) null keyword
c) is operator
d) Task.WhenAll()
Answer: a) ?? operator
Explanation: The ??
operator is the null-coalescing operator in C#, which is used to provide a default value for nullable value types. If the nullable type is null, it will return the default value specified after the ??
operator. This helps avoid null reference exceptions when dealing with nullable types.
80. Which of the following is a key feature of C# 7.0
that simplifies working with tuples?
a) Pattern matching
b) Task objects
c) Named tuples
d) init properties
Answer: c) Named tuples
Explanation: C# 7.0 introduced named tuples, which allow you to name the elements of a tuple for better readability and maintainability. This feature makes it easier to work with tuples by providing meaningful names to the tuple fields, improving code clarity when accessing those values.
81. Which of the following C# features allows you to
perform pattern matching on types in switch expressions?
a) is keyword
b) switch keyword with type patterns
c) new keyword
d) readonly keyword
Answer: b) switch keyword with type patterns
Explanation: In C# 7.0 and later, the switch
statement supports type patterns, allowing you to match types directly in switch
expressions. This makes it easier to perform pattern matching and execute code based on the type of an object, streamlining conditional logic.
82. In C# 9.0, which of the following is a benefit of
using record types over class types?
a) They allow reference equality by default.
b) They provide value-based equality and immutable properties by default.
c) They are mutable by default and have reference-based equality.
d) They can only be used in generic classes.
Answer: b) They provide value-based equality and
immutable properties by default.
Explanation: In C# 9.0, record types are designed for immutability and value-based equality. This means that when you create a record, its properties are immutable by default, and two instances of a record are considered equal if their data is the same, not by reference. This makes them ideal for representing data objects.
83. Which of the following methods is used to handle
errors in asynchronous programming in C#?
a) try-catch blocks with await
b) Task.Wait()
c) Task.WhenAll()
d) Parallel.ForEach()
Answer: a) try-catch blocks with await
Explanation: In C#, asynchronous errors can be handled using try-catch
blocks around await
expressions. This allows exceptions thrown in asynchronous methods to be caught and handled in the same way as synchronous errors, preventing unhandled exceptions from crashing the program.
84. In C# 8.0, which of the following allows you to
asynchronously process streams of data without blocking the calling thread?
a) Parallel.ForEach()
b) Task.WhenAll()
c) async streams with await foreach
d) await keyword with Task.Run()
Answer: c) async streams with await foreach
Explanation: In C# 8.0, async streams allow asynchronous iteration over data using the await foreach
construct. This enables processing data streams without blocking the calling thread, making it ideal for scenarios like reading from a file or fetching data over a network asynchronously.
85. What is the primary purpose of the async keyword in
C#?
a) To define methods that run synchronously.
b) To specify a method that performs asynchronous operations and returns Task.
c) To define methods that are parallelized across multiple threads.
d) To define a method that does not return any value.
Answer: b) To specify a method that performs
asynchronous operations and returns Task.
Explanation: The async
keyword in C# is used to define a method that can perform asynchronous operations. These methods typically return a Task
or Task<T>
, allowing the execution of non-blocking, asynchronous code using the await
keyword within them.
86. Which of the following is a valid use case for the async
and await keywords in C#?
a) Running CPU-bound operations in parallel.
b) Running asynchronous operations that might take time, such as I/O or network
requests.
c) Performing calculations in a multi-threaded environment.
d) Handling synchronous file operations efficiently.
Answer: b) Running asynchronous operations that might
take time, such as I/O or network requests.
Explanation: The async
and await
keywords in C# are used to write asynchronous code, particularly for operations that involve waiting, such as network calls or I/O tasks (e.g., reading files or making HTTP requests). They allow the program to continue executing other tasks without blocking the main thread while waiting for the long-running operation to complete.
87. Which of the following C# keywords ensures that a
method is only called once during object initialization and is often used with init
properties?
a) readonly
b) set
c) readonly init
d) init
Answer: d) init
Explanation: The init
keyword in C# is used to define properties that can only be set during object initialization, either in a constructor or with an object initializer. It ensures that the property is assigned a value only once during the creation of the object, making it immutable after initialization.
88. Which of the following statements about Task.WhenAll()
is true in C#?
a) It returns when the first task completes.
b) It executes the tasks in parallel but does not wait for all tasks to
complete.
c) It waits for all tasks to complete and returns their results as an array.
d) It cancels all tasks once the first task completes.
Answer: c) It waits for all tasks to complete and
returns their results as an array.
Explanation: Task.WhenAll()
is used to execute multiple tasks concurrently and waits for all of them to finish. It then returns an array of the results of each task. If any task fails, the returned task is completed with an exception.
89. In C# 9.0, which feature enables you to copy an
object with a modification to some of its properties without changing the
original object?
a) readonly fields
b) with expressions
c) init properties
d) default keyword
Answer: b) with expressions
Explanation: In C# 9.0, the with expression allows you to create a copy of an object and modify specific properties without altering the original object. This feature is mainly used with record types, enabling concise immutability and value-based equality while allowing partial updates to the object.
90. Which of the following C# features improves
null-safety by explicitly defining whether a reference type is nullable or
non-nullable?
a) Pattern matching
b) Nullable reference types
c) async methods
d) readonly properties
Answer: b) Nullable reference types
Explanation: In C# 8.0 and later, nullable reference types improve null-safety by allowing developers to explicitly specify whether a reference type can be null. This feature helps to prevent null reference exceptions by providing warnings when a nullable reference type is dereferenced without checking for null.
91. Which of the following expressions is used in C# to
define a local function?
a) func
b) delegate
c) local
d) void
Answer: b) delegate
Explanation: In C#, a local function is defined within a method, and it can be declared using the delegate
keyword or directly by specifying the return type and parameters. While a delegate
can be used for defining a local function, you can also define a local function directly without the delegate keyword, but the answer here refers to it as a key concept.
92. What does the ?? operator in C# do?
a) It throws an exception if the value is null.
b) It returns the value on the left side if it is not null, otherwise, it
returns the value on the right side.
c) It checks if a variable is of a nullable type.
d) It casts a nullable type to a non-nullable type.
Answer: b) It returns the value on the left side if
it is not null, otherwise, it returns the value on the right side.
Explanation: The ??
operator, known as the null-coalescing operator, checks if the left operand is null. If it is not null, it returns the left operand; otherwise, it returns the right operand. This is commonly used to provide a default value when dealing with nullable types.
93. What is the default behavior of a record type in C#
regarding immutability?
a) The properties are immutable only if explicitly marked
with readonly.
b) The properties are mutable by default.
c) The properties are immutable by default and must be initialized in the
constructor or object initializer.
d) record types do not support immutability.
Answer: c) The properties are immutable by default
and must be initialized in the constructor or object initializer.
Explanation: In C# 9.0, record types are designed to be immutable by default. Their properties can only be assigned during object initialization or through a constructor. They support value-based equality, meaning two records with the same values are considered equal.
94. Which of the following C# features allows you to
define an immutable object where the value-based equality is determined
automatically?
a) readonly keyword
b) record types
c) sealed classes
d) default keyword
Answer: b) record types
Explanation: In C# 9.0, record types provide a way to define immutable objects with automatically generated value-based equality. Unlike regular classes, records are designed to have equality comparisons based on their values, not references. This makes record types ideal for representing data that should not change after creation.
95. What is the primary difference between Task.WhenAny()
and Task.WhenAll() in C#?
a) Task.WhenAny() waits for all tasks to finish, while Task.WhenAll()
waits for the first task to complete.
b) Task.WhenAll() waits for all tasks to finish, while Task.WhenAny() waits for
the first task to complete.
c) Both methods behave the same.
d) Task.WhenAny() can only be used with asynchronous methods, while Task.WhenAll()
is used for synchronous methods.
Answer: b) Task.WhenAll() waits for all tasks to
finish, while Task.WhenAny() waits for the first task to complete.
Explanation: Task.WhenAll() waits for all provided tasks to complete and returns when every task finishes, allowing you to retrieve the results from all tasks. Task.WhenAny(), on the other hand, returns as soon as any one of the provided tasks completes, allowing you to process the first completed task while others continue running.
96. Which of the following C# 8.0 features helps prevent
null reference exceptions by making reference types nullable only when
explicitly specified?
a) async and await
b) Pattern matching
c) Nullable reference types
d) init properties
Answer: c) Nullable reference types
Explanation: Nullable reference types was introduced in C# 8.0 to improve null safety. By default, reference types are considered non-nullable, and you must explicitly mark them as nullable using the ?
syntax (e.g., string?
). This helps prevent null reference exceptions by providing compile-time warnings when a null value is assigned to a reference type that isn't marked as nullable.
97. What is the output of the following C# code?
string str = null;
string result = str ?? "Default";
Console.WriteLine(result);
a) null
b) Default
c) str
d) Compilation error
Answer: b) Default
Explanation: The ??
(null-coalescing) operator in C# checks if the value on the left (str
) is null
. If it is null
, it returns the value on the right ("Default"
). Since str
is null
, the operator will return "Default"
. Therefore, the value of result
will be "Default"
, and it will be printed to the console.
98. Which of the following features of C# 9.0 allows you
to create more declarative and concise data structures with built-in equality
checks?
a) readonly properties
b) init properties
c) record types
d) Pattern matching
Answer: c) record types
Explanation: Introduced in C# 9.0, record types provide a concise way to create immutable data structures with built-in equality checks. They automatically implement value-based equality, making it easier to compare instances based on their content, which is useful for scenarios like data transfer objects (DTOs) and models.
99. In C# 9.0, which of the following statements is true
about with expressions?
a) They can be used to modify the value of mutable objects.
b) They create a copy of an object and modify certain properties, leaving the
original object unchanged.
c) They only work with classes, not structs or records.
d) They can be used to create deep copies of objects.
Answer: b) They create a copy of an object and modify
certain properties, leaving the original object unchanged.
Explanation: With expressions in C# 9.0 are used specifically with record types, allowing you to create a new object that is a copy of an existing one with modifications to specific properties. This creates an immutable pattern, where the original object remains unchanged, and only the new instance reflects the modifications. With expressions do not modify mutable objects, as they are designed to work with immutable record types, providing a concise way to update properties.
100. Which of the following is the purpose of the async
modifier in C#?
a) It marks a method to run synchronously.
b) It indicates that a method will perform asynchronous operations and may
contain await expressions.
c) It prevents the method from returning a result.
d) It allows the method to execute in parallel on multiple threads.
Answer: b) It indicates that a method will perform
asynchronous operations and may contain await expressions.
Explanation: The async modifier in C# is used to mark a method that performs asynchronous operations, allowing the use of await inside the method. It ensures that the method will return a Task (or Task<T>), which represents an ongoing operation that can be awaited. This enables the method to perform non-blocking operations, typically for I/O-bound tasks such as reading files or making network requests.
101. Which of the following features, introduced in C#
9.0, provides value-based equality, immutability, and supports copy
functionality using with expressions?
a) struct types
b) class types
c) record types
d) enum types
Answer: c) record types
Explanation: Record types in C# 9.0 are designed to provide value-based equality by default, meaning two record instances are considered equal if their properties are equal. They are immutable by default, meaning their properties cannot be modified after they are set, unless marked as mutable. With expressions allow creating copies of records with modified properties while keeping the original unchanged.
102. Which of the following best describes the null-coalescing
assignment operator (??=) introduced in C# 8.0?
a) It assigns a value to a variable only if the variable is
not null.
b) It checks if a variable is null and assigns a default value if true.
c) It checks if a variable is null and throws an exception if true.
d) It prevents assigning null to a variable.
Answer: b) It checks if a variable is null and
assigns a default value if true.
Explanation: The null-coalescing assignment operator (??=) checks if the variable on the left is null
. If it is null
, the operator assigns the value on the right to the variable. This simplifies code by combining the check and assignment into a single operation.
103. Which of the following methods is used to execute a
given task asynchronously in a non-blocking manner in C#?
a) Task.Run()
b) Task.Wait()
c) Task.Delay()
d) Task.WhenAll()
Answer: a) Task.Run()
Explanation: Task.Run() is used to execute a task asynchronously on a separate thread, allowing non-blocking execution. It is typically used to offload CPU-bound work to a background thread without blocking the main thread. This method returns a Task, enabling further operations once the task completes.
104. What is the output of the following C# code?
int? x = 5;
Console.WriteLine(x ??= 10);
a) 5
b) 10
c) null
d) Compilation error
Answer: a) 5
Explanation: The ??= operator assigns the value on the right (10) only if the left-hand value is null. In this case, x
is already 5 (not null), so the value of x
remains 5, and 5 is printed. If x
had been null, it would have been assigned 10.
105. What is the purpose of the Task.WhenAny() method in
C#?
a) It returns a Task that will complete once all tasks
complete.
b) It executes the provided tasks in parallel and waits for any one of them to
complete.
c) It executes the provided tasks sequentially and returns the first task that
completes.
d) It waits for the first task to complete and cancels the others.
Answer: b) It executes the provided tasks in parallel
and waits for any one of them to complete.
Explanation: Task.WhenAny() takes multiple tasks and waits for the first one to complete, returning that task. It does not wait for all tasks to complete, and it does not cancel the remaining tasks. This is useful when you need to proceed as soon as one task finishes, regardless of the others.
106. Which C# feature introduced in version 8.0 enables
you to perform asynchronous iteration over a collection using await foreach?
a) Asynchronous streams
b) Task.Run()
c) Parallel.ForEach()
d) async methods
Answer: a) Asynchronous streams
Explanation: Asynchronous streams in C# 8.0 allow you to iterate over data asynchronously using await foreach
. This enables processing streams of data that are produced asynchronously without blocking the calling thread. It is particularly useful when working with data that arrives over time, such as reading from a file or receiving data from a network.
107. Which of the following is true about C#'s init
properties introduced in C# 9.0?
a) init properties can only be set during object
initialization.
b) init properties can be changed at any time during object lifetime.
c) init properties must be initialized within the constructor.
d) init properties behave like readonly properties but can be set after object
creation.
Answer: a) init properties can only be set during
object initialization.
Explanation: Init properties in C# 9.0 can only be set during the initialization of an object, either in the constructor or object initializer. After the object is fully initialized, the init
properties cannot be modified, making them effectively immutable post-construction. This feature provides a way to define immutable properties with flexibility during object creation.
108. Which of the following methods can be used to
process multiple tasks asynchronously and returns the results as an array of
values in C#?
a) Task.WhenAny()
b) Task.WhenAll()
c) Parallel.ForEach()
d) Task.Run()
Answer: b) Task.WhenAll()
Explanation: Task.WhenAll() allows you to run multiple tasks concurrently and returns a task that completes when all the provided tasks have finished. It returns an array of the results from the tasks if the tasks return values (e.g., Task<T>
). It ensures that all tasks are awaited and completed before continuing execution.
109. Which of the following C# features was introduced in
C# 7.0 to simplify working with tuples?
a) Record types
b) Async streams
c) Named tuples
d) Pattern matching
Answer: c) Named tuples
Explanation: Named tuples in C# 7.0 allow you to define tuple elements with meaningful names, improving code readability and maintainability. Before C# 7.0, tuple elements were accessed by position (Item1, Item2, etc.), but with named tuples, you can access them using custom names. This feature simplifies working with tuples and provides more clarity when accessing tuple values.
110. Which of the following methods is used to execute a
block of code in parallel in C#?
a) Task.WhenAll()
b) Parallel.ForEach()
c) await keyword
d) Task.Delay()
Answer: b) Parallel.ForEach()
Explanation: Parallel.ForEach() is used to execute a block of code in parallel over a collection of data, improving performance for CPU-bound tasks. It divides the work across multiple threads, allowing each iteration to run concurrently, which speeds up the processing of large datasets. This method is part of the Task Parallel Library (TPL) and is ideal for performing operations in parallel without managing threads manually.
111. Which of the following C# features allows you to
match a value against a specific pattern and extract its value using a switch
statement?
a) Pattern matching
b) is operator
c) readonly keyword
d) async methods
Answer: a) Pattern matching
Explanation: Pattern matching in C# allows you to match a value against a specific pattern, such as types, ranges, or conditions, within a switch statement. It enhances the expressiveness and readability of the code by enabling type checks and value extraction in a concise manner. Introduced in C# 7.0 and expanded in later versions, pattern matching allows more flexible and powerful switch expressions.
112. Which of the following C# 8.0 features makes it
possible to define a reference type as nullable or non-nullable?
a) Nullable reference types
b) Async streams
c) Pattern matching
d) init properties
Answer: a) Nullable reference types
Explanation: C# 8.0 introduced nullable reference types to distinguish between nullable and non-nullable reference types. This feature allows developers to explicitly specify whether a reference type can hold a null value or not. It helps to avoid null reference exceptions by providing compile-time warnings.
113. Which of the following keywords in C# is used to
define a read-only field or property, which cannot be modified after
initialization?
a) readonly
b) readonly and init
c) private
d) const
Answer: a) readonly
Explanation: The readonly
keyword in C# is used to define fields that can only be assigned a value during initialization or within a constructor. Once assigned, the value cannot be modified. This ensures immutability after initialization, unlike const
, which must be assigned at compile time.
114. Which of the following is true about C# 8.0’s
asynchronous streams?
a) Asynchronous streams allow using await foreach to iterate
over asynchronous data.
b) Asynchronous streams allow for concurrent processing of multiple tasks.
c) Asynchronous streams allow synchronous iteration of large data collections.
d) Asynchronous streams are used to handle multiple threads synchronously.
Answer: a) Asynchronous streams allow using await
foreach to iterate over asynchronous data.
Explanation: C# 8.0 introduced asynchronous streams, allowing the use of await foreach
to asynchronously iterate over data that is produced over time. This enables efficient handling of large datasets or operations that involve I/O without blocking the main thread. It is specifically designed to work with asynchronous data sources, like streams.
115. Which of the following is a valid C# expression to
enable nullable reference types in a project?
a) #nullable enable
b) nullable enable
c) #enable nullable
d) nullable reference types
Answer: a) #nullable enable
Explanation: In C# 8.0 and later, #nullable enable
is used to enable nullable reference types for a project, making it possible to explicitly define whether reference types can be null. This directive applies to the file in which it is declared and helps avoid null reference exceptions. It is placed at the top of a C# file or within a project file.
116. In C# 8.0, which of the following allows you to
handle potentially nullable references in a safer manner?
a) try-catch blocks
b) Nullable reference types
c) await keyword
d) Pattern matching
Answer: b) Nullable reference types
Explanation: In C# 8.0, nullable reference types help handle potentially null references safely by providing compile-time warnings when a nullable reference is dereferenced without null checking. This feature helps developers write more robust code by explicitly defining which reference types can be null. It reduces the likelihood of null reference exceptions at runtime.
117. Which of the following C# 7.0 features allows you to
work with tuples more effectively by naming their elements?
a) Records
b) Named tuples
c) Default literals
d) Pattern matching
Answer: b) Named tuples
Explanation: C# 7.0 introduced named tuples, allowing you to assign names to the elements of a tuple for better readability and maintainability. This makes it easier to access and understand tuple values by referring to them by their names instead of using index-based access. Named tuples provide a more descriptive way of working with tuple data.
118. What is the primary advantage of using the async and
await keywords in C#?
a) They make operations run on separate threads.
b) They ensure that operations are always performed in parallel.
c) They enable non-blocking asynchronous programming to avoid freezing the user
interface.
d) They execute synchronous methods asynchronously.
Answer: c) They enable non-blocking asynchronous
programming to avoid freezing the user interface.
Explanation: The primary advantage of using async
and await
in C# is that they allow asynchronous programming, enabling non-blocking operations. This prevents the UI from freezing during long-running tasks by running operations in the background. It improves responsiveness, especially in applications with a user interface.
119. Which C# feature introduced in C# 9.0 allows you to define a data type that can automatically implement value-based equality and other standard functionality?
a) class types
b) record types
c) readonly types
d) delegate types
Answer: b) record types
Explanation: C# 9.0 introduced record types, which provide a simple way to define immutable data types with value-based equality. Record types automatically implement functionality like Equals()
, GetHashCode()
, and ToString()
. They are designed for scenarios where the identity of the object is determined by its data rather than its reference.
120. Which of the following is true about C#'s async and await
keywords when dealing with asynchronous methods?
a) async allows methods to run synchronously, while await executes
them asynchronously.
b) async modifies the method signature to indicate it will run asynchronously,
while await is used to pause execution until the asynchronous operation
completes.
c) await only works inside synchronous methods.
d) async cannot be used with await.
Answer: b) async modifies the method signature to
indicate it will run asynchronously, while await is used to pause execution
until the asynchronous operation completes.
Explanation: The async
keyword modifies a method to indicate it will run asynchronously, enabling the use of await
inside it. The await
keyword pauses the execution of the method until the asynchronous operation completes, without blocking the thread. This combination allows efficient handling of asynchronous tasks, especially in UI applications.
121. Which of the following features introduced in C# 7.0
allows methods to return multiple values in the form of tuples?
a) ref keyword
b) out keyword
c) Tuples
d) params keyword
Answer: c) Tuples
Explanation: C# 7.0 introduced tuples, allowing methods to return multiple values as a single, compound data type. Tuples provide a simple and efficient way to group multiple values together, without the need for custom classes or structs. This feature enables cleaner code and better handling of multiple return values.
122. Which of the following correctly demonstrates the
use of pattern matching with a switch expression in C# 8.0 or later?
a) var result = x switch
{
int i =>
"Integer",
string s =>
"String",
_ =>
"Unknown"
};
b) var result = switch(x)
{
int i => "Integer",
string s =>
"String",
_ =>
"Unknown"
};
c) var result = switch(x)
{
case int i:
"Integer",
case string s:
"String",
default:
"Unknown"
};
d) var result = x case int i => "Integer";
Answer: a)
var result = x switch
{
int i =>
"Integer",
string s =>
"String",
_ =>
"Unknown"
};
Explanation: The correct way to use pattern matching with a switch expression in C# 8.0 or later is as follows:
{
int i => "Integer",
string s => "String",
_ => "Unknown"
};
This syntax allows for matching the type of x against patterns and returning corresponding values. The _ is used as a wildcard to handle all other cases.
123. What will be the output of the following C# code?
int? x = null;
string result = x?.ToString() ?? "Null";
Console.WriteLine(result);
a) null
b) Null
c) x
d) ToString
Answer: b) Null
Explanation: The code uses the null-conditional operator (?.
) to safely call ToString()
only if x
is not null. Since x
is null
, x?.ToString()
evaluates to null
. The null-coalescing operator (??
) then returns "Null"
as a fallback value.
124. Which of the following is the purpose of the async
keyword in C#?
a) It allows the method to execute asynchronously on a
separate thread.
b) It marks a method that will contain an asynchronous operation and can use await.
c) It makes a method run synchronously.
d) It helps in defining the return type of the method as Task.
Answer: b) It marks a method that will contain an
asynchronous operation and can use await.
Explanation: The async
keyword in C# is used to mark a method that will contain asynchronous operations. It allows the method to use the await
keyword, enabling the method to execute asynchronously without blocking the calling thread. This helps improve performance, especially in applications with UI or I/O-bound operations.
125. Which C# version introduced switch expressions,
enabling concise pattern matching?
a) C# 8.0
b) C# 9.0
c) C# 7.0
d) C# 10.0
Answer: a) C# 8.0
Explanation: C# 8.0 introduced switch expressions, enabling more concise and expressive pattern matching. This feature allows you to use the switch
keyword in a more compact form, directly returning values based on patterns, which enhances readability and reduces boilerplate code.
126. Which of the following C# features improves working
with nullable types, preventing null reference exceptions by clearly defining
nullable reference types?
a) readonly
b) Nullable reference types
c) default keyword
d) unsafe code
Answer: b) Nullable reference types
Explanation: The feature that improves working with nullable types in C# and helps prevent null reference exceptions is Nullable reference types. Introduced in C# 8.0, it allows developers to explicitly define which reference types can be null and which cannot, providing compile-time warnings when nullable references are dereferenced without proper null checks. This significantly reduces the risk of null reference exceptions.
127. Which C# method is used to execute tasks in parallel
and can handle multiple tasks simultaneously without blocking the calling
thread?
a) Parallel.ForEach()
b) Task.WhenAll()
c) async
d) ThreadPool.QueueUserWorkItem()
Answer: a) Parallel.ForEach()
Explanation: Parallel.ForEach()
executes multiple tasks concurrently by distributing them across available threads, enabling parallel processing. This method helps improve performance in CPU-bound operations without blocking the calling thread. It is ideal for processing collections or ranges in parallel.
128. What is the primary benefit of using the readonly
keyword in C#?
a) To prevent a variable from being modified after it is
initialized.
b) To mark a method that cannot be overridden.
c) To define a constant value.
d) To make a variable thread-safe.
Answer: a) To prevent a variable from being modified
after it is initialized.
Explanation: The primary benefit of using the readonly
keyword in C# is to prevent a variable from being modified after it has been initialized. A readonly
field can only be assigned a value during its declaration or inside a constructor, ensuring that its value remains constant throughout the object's lifetime. This helps maintain immutability and reduces the risk of accidental modifications.
129. Which of the following C# features allows a method
to continue executing without blocking the calling thread, typically used for
I/O-bound tasks?
a) Task.Run()
b) Thread.Sleep()
c) async and await
d) Parallel.ForEach()
Answer: c) async and await
Explanation: The async
and await
keywords in C# enable asynchronous programming, allowing a method to perform non-blocking operations. These keywords are typically used for I/O-bound tasks, such as file operations or network requests, enabling the method to continue executing without blocking the calling thread. This improves application responsiveness and performance, particularly in UI or server-side applications.
130. Which of the following expressions creates a new
instance of a record type in C#?
a) new RecordType() { Property1 = 1, Property2 =
"hello" };
b) new RecordType { Property1 = 1, Property2 = "hello" };
c) new RecordType() => { Property1 = 1, Property2 = "hello" };
d) new RecordType { 1, "hello" };
Answer: b) new RecordType { Property1 = 1, Property2
= "hello" };
Explanation: In C#, a record type can be instantiated using the syntax new RecordType { Property1 = 1, Property2 = "hello" }
. This creates a new instance of the record and initializes its properties. Record types are designed for immutable data and this syntax allows for easily setting their values.
131. Which of the following best describes the behavior
of nullable reference types in C# 8.0 and later?
a) Reference types are nullable by default unless specified
as non-nullable.
b) Reference types are always non-nullable by default.
c) Reference types are only nullable if they are explicitly declared as such.
d) Reference types cannot be null in C# 8.0 and later.
Answer: a) Reference types are nullable by default
unless specified as non-nullable.
Explanation: In C# 8.0 and later, nullable reference types are enabled by default, meaning reference types are considered nullable unless explicitly declared as non-nullable. This behavior allows developers to handle potential null values more safely by providing compile-time warnings when a nullable reference type is dereferenced without proper null checking. To define a reference type as non-nullable, the #nullable enable
directive must be used, and the type must be marked accordingly.
132. Which C# feature introduced in C# 7.0 allows you to
deconstruct an object into its constituent parts?
a) ref keyword
b) Pattern matching
c) Deconstruction
d) Tuples
Answer: c) Deconstruction
Explanation: C# 7.0 introduced deconstruction, which allows you to break down an object into its constituent parts, such as properties or fields, using a straightforward syntax. This is commonly used with tuples or custom types that define a Deconstruct
method. It simplifies extracting multiple values from an object and assigning them to individual variables.
133. Which of the following is true about the use of init
properties in C# 9.0?
a) init properties can be set after object initialization.
b) init properties are only available in records.
c) init properties can only be set during object initialization or through an
object initializer.
d) init properties are immutable and cannot be set at all.
Answer: c) init properties can only be set during
object initialization or through an object initializer.
Explanation: In C# 9.0, init
properties allow you to set a property's value during object initialization, either directly in the constructor or through an object initializer. Once the object is fully initialized, the property becomes immutable and cannot be modified afterward. This provides a way to create immutable objects while still allowing property values to be set at creation time.
134. What is the default behavior of reference types in
C# when nullable reference types are enabled?
a) Reference types are nullable by default, unless
explicitly marked as non-nullable.
b) Reference types cannot be null when nullable reference types are enabled.
c) All reference types are implicitly treated as non-nullable.
d) Reference types are non-nullable by default but can be marked as nullable.
Answer: a) Reference types are nullable by default,
unless explicitly marked as non-nullable.
Explanation: When nullable reference types are enabled in C# 8.0 or later, reference types are considered nullable by default, meaning they can hold a null
value. To specify that a reference type cannot be null
, it must be explicitly marked as non-nullable using a !
annotation or other appropriate configuration. This feature helps prevent null reference exceptions by providing compile-time warnings.
135. What is the output of the following C# code?
int? x = 5;
int? y = null;
Console.WriteLine(x ?? y);
a) null
b) 5
c) y
d) Compilation error
Answer: b) 5
Explanation: The ??
(null-coalescing) operator checks if the left-hand operand (x
) is null
. Since x
is 5
(not null), the operator returns x
. Therefore, the output of Console.WriteLine(x ?? y)
is 5
.
136. Which of the following is used to run an
asynchronous method in parallel without blocking the main thread in C#?
a) Parallel.ForEach()
b) Task.Run()
c) ThreadPool.QueueUserWorkItem()
d) async keyword
Answer: b) Task.Run()
Explanation: Task.Run()
is used to run an asynchronous method in parallel, allowing the method to execute on a separate thread without blocking the main thread. This is particularly useful for offloading work that can run concurrently, such as I/O-bound or CPU-bound operations, and ensures that the main thread remains responsive, especially in UI applications.
137. Which of the following is true about Task.WhenAll()
in C#?
a) It executes multiple tasks sequentially and waits for all
of them to complete.
b) It runs multiple tasks concurrently and returns when any of them completes.
c) It waits for all the tasks to complete and returns an array of results.
d) It executes tasks in a parallel manner and returns a task that will never
complete.
Answer: c) It waits for all the tasks to complete and
returns an array of results.
Explanation: Task.WhenAll()
in C# runs multiple tasks concurrently and waits for all of them to complete. It returns a Task
that represents the completion of all the provided tasks, and if the tasks return results, it returns an array of those results. This method is useful for aggregating results from multiple asynchronous operations.
138. Which of the following is a valid C# expression to
use the switch expression introduced in C# 8.0 for a variable of type object?
a) var result = obj switch
{
int i =>
"Integer",
string s =>
"String",
_ =>
"Unknown"
};
b) var result = obj case int i => "Integer";
c) var result = switch(obj)
{
case int i:
"Integer",
case string s:
"String",
default:
"Unknown"
};
d) var result = obj match
{
int i =>
"Integer",
string s => "String",
_ =>
"Unknown"
};
Answer: a) var result = obj switch
{
int i =>
"Integer",
string s =>
"String",
_ =>
"Unknown"
};
Explanation: The correct syntax for using the switch expression in C# 8.0 is var result = obj switch { ... }
. In this example, the expression checks the type of obj
and returns different results based on the type. The _
serves as a fallback for cases that don't match any specified pattern, such as when obj
is of an unknown type.
139. Which of the following C# features allows you to
define and manipulate data as a sequence of elements asynchronously?
a) async and await
b) async streams
c) LINQ
d) Task.WhenAny()
Answer: b) async streams
Explanation: Introduced in C# 8.0, async streams allow you to work with asynchronous data by using the await foreach
loop. This enables efficient handling of large datasets or I/O-bound operations, where elements are produced over time and processed asynchronously without blocking the main thread.
140. Which of the following does the ?? operator do in
C#?
a) It assigns a value to a variable if the variable is null.
b) It checks if a variable is not null and assigns a default value.
c) It throws a NullReferenceException if the value is null.
d) It checks if a variable is null and throws an exception if true.
Answer: a) It assigns a value to a variable if the
variable is null.
Explanation: The ??
operator in C# is the null-coalescing operator, which checks if a variable is null. If the variable is null, it assigns the value on the right-hand side of the operator. If the variable is not null, it simply returns the value of the variable. This helps in providing default values for nullable types.
141. Which of the following C# features allows you to
prevent null reference exceptions by making reference types nullable or
non-nullable?
a) Value types
b) Null-conditional operators
c) Nullable reference types
d) Asynchronous streams
Answer: c) Nullable reference types
Explanation: Introduced in C# 8.0, nullable reference types help prevent null reference exceptions by allowing developers to explicitly define whether reference types can be null. This feature provides compile-time warnings when nullable reference types are dereferenced without proper null checks, improving code safety and reducing the risk of runtime errors.
142. Which of the following will be the result of the
following C# code?
var person = new { Name = "John", Age = 30 };
Console.WriteLine(person.Name);
a) Compilation error
b) John
c) Name
d) person.Name
Answer: b) John
Explanation: The code creates an anonymous object person
with properties Name
and Age
. When you access person.Name
, it refers to the Name
property of the anonymous object, which is "John"
. Therefore, the output of Console.WriteLine(person.Name)
will be the value of the Name
property, which is "John"
.
143. Which C# feature, introduced in C# 8.0, allows you
to use await foreach to iterate over asynchronous collections?
a) Asynchronous streams
b) Asynchronous delegates
c) Task-based asynchronous patterns
d) Parallel LINQ
Answer: a) Asynchronous streams
Explanation: Introduced in C# 8.0, asynchronous streams allow you to use the await foreach
loop to iterate over collections that are being produced asynchronously. This is particularly useful for working with I/O-bound tasks where data is generated or received over time, allowing you to process elements as they become available without blocking the main thread.
144. Which of the following will be the result of the
following C# code?
int? number = null;
int result = number ?? 5;
Console.WriteLine(result);
a) null
b) 0
c) 5
d) Compilation error
Answer: c) 5
Explanation: The ??
operator is the null-coalescing operator, which checks if the left-hand operand (number
) is null
. Since number
is null
, the operator assigns the value on the right-hand side (5) to result
. Therefore, the output of Console.WriteLine(result)
will be 5
.
145. Which C# version introduced async streams to support
asynchronous iteration over collections using the await foreach syntax?
a) C# 7.0
b) C# 8.0
c) C# 9.0
d) C# 10.0
Answer: b) C# 8.0
Explanation: C# 8.0 introduced async streams, allowing developers to asynchronously iterate over collections using the await foreach
syntax. This feature is useful for working with data that is retrieved or processed asynchronously, such as streaming data or I/O-bound tasks, without blocking the main thread.
146. What is the main difference between a struct and a record
in C#?
a) record types are mutable, and struct types are immutable.
b) struct types are always passed by reference, and record types are passed by
value.
c) record types support value-based equality and immutability, while struct
types do not.
d) struct types cannot have methods, while record types can.
Answer: c) record types support value-based equality
and immutability, while struct types do not.
Explanation: In C#, record types are designed to provide value-based equality (i.e., comparing the contents of the object) and immutability by default, which makes them ideal for defining immutable data models. In contrast, struct types are value types that are compared by their memory address (reference-based equality) and are mutable by default, although immutability can be enforced manually.
147. Which of the following C# 9.0 features allows you to
perform a deep copy of an immutable object by using the with expression?
a) struct types
b) record types
c) tuple types
d) async streams
Answer: b) record types
Explanation: In C# 9.0, record types introduce the with
expression, which allows you to create a deep copy of an immutable object while optionally modifying some of its properties. This feature is particularly useful for working with immutable objects, providing a concise and readable way to create modified copies of records without altering the original object.
148. What is the output of the following code in C#?
int[] numbers = { 1, 2, 3, 4 };
var query = numbers.Where(x => x % 2 == 0);
Console.WriteLine(query.Count());
a) 2
b) 4
c) 3
d) 1
Answer: a) 2
Explanation: The Where
method filters the array to only include even numbers, so the resulting sequence contains { 2, 4 }
. The Count()
method then counts the number of elements in the filtered sequence, which is 2. Therefore, the output of Console.WriteLine(query.Count())
is 2
.
149. Which of the following correctly defines a nullable
reference type in C# 8.0 or later?
a) string? name = "John";
b) nullable string name = "John";
c) string? name = null;
d) string name = null;
Answer: a) string? name = "John";
Explanation: In C# 8.0 and later, nullable reference types are defined using the ?
syntax, which indicates that the reference type (like string
) can hold either a value or null
. By declaring string? name
, you're explicitly allowing the variable name
to be null
, which helps prevent null reference exceptions when working with reference types.
150. Which of the following features introduced in C# 7.0
allows methods to accept an unspecified number of arguments of the same type?
a) params keyword
b) ref keyword
c) out keyword
d) Tuples
Answer: a) params keyword
Explanation: In C# 7.0, the params
keyword allows a method to accept a variable number of arguments of the same type. It enables the passing of an array of arguments to a method, providing flexibility in how arguments are passed without needing to specify the exact number. This is particularly useful when you want to handle a variable number of input values.
151. Which C# feature introduced in C# 9.0 allows you to
define a property that can only be set during initialization?
a) readonly
b) init
c) const
d) static
Answer: b) init
Explanation: The init
keyword, introduced in C# 9.0, allows properties to be set only during object initialization, either directly in the constructor or through an object initializer. After initialization, these properties cannot be modified, ensuring immutability. This is useful for creating immutable objects with flexibility in setting values at the time of creation.
152. Which of the following will result in an error when
trying to access a nullable type in C#?
a) x?.ToString()
b) x.GetValueOrDefault()
c) x.Value without checking for null
d) x.HasValue
Answer: c) x.Value without checking for null
Explanation: In C#, if you try to access the .Value
property of a nullable type (Nullable<T>
) without first checking whether it has a value (i.e., whether HasValue
is true), it will result in a InvalidOperationException
at runtime if the value is null
. To safely access the value, you should either check HasValue
or use the null-conditional operator (?.
).
153. What will be the output of the following C# code?
var person = new { Name = "Jane", Age = 25 };
var newPerson = person with { Age = 30 };
Console.WriteLine(newPerson.Age);
a) 25
b) 30
c) Compilation error
d) null
Answer: b) 30
Explanation: In C# 9.0, records allow the use of the with
expression to create a copy of an object with modified values. Here, newPerson
is a new record that is a copy of person
, but with the Age
property changed to 30
. Therefore, Console.WriteLine(newPerson.Age)
outputs 30
.
154. Which of the following C# features enables a concise
way to match complex types in switch expressions?
a) Pattern matching
b) try-catch blocks
c) ref keyword
d) async methods
Answer: a) Pattern matching
Explanation: Pattern matching, introduced in C# 7.0 and enhanced in later versions, allows for a concise way to check and match complex types within switch
expressions. It enables you to match data types, values, or conditions directly in the switch
statement, improving readability and reducing the need for multiple conditional checks.
155. Which of the following is true about the async and await
keywords in C#?
a) async makes a method return Task or Task<T>, and await
can be used to pause the method until a Task completes.
b) async and await are only for methods that perform I/O operations.
c) async marks a method as synchronous, and await makes it asynchronous.
d) async and await are used to define parallel tasks that execute on separate
threads.
Answer: a) async makes a method return Task or Task<T>,
and await can be used to pause the method until a Task completes.
Explanation: In C#, the async
keyword marks a method as asynchronous, allowing it to return a Task
or Task<T>
. The await
keyword is used within an asynchronous method to pause the execution of the method until the awaited Task
completes, allowing for non-blocking operations. This makes it easier to handle asynchronous programming without blocking the main thread.
156. Which of the following C# constructs allows you to
define a method that can be used to process multiple tasks in parallel?
a) Task.WhenAny()
b) Task.WhenAll()
c) Parallel.ForEach()
d) Parallel.Invoke()
Answer: b) Task.WhenAll()
Explanation: Task.WhenAll()
allows you to run multiple tasks in parallel and wait for all of them to complete. It returns a task that represents the completion of all provided tasks, making it useful for managing and processing multiple asynchronous operations concurrently.
157. Which of the following methods is used to check if a
Task has completed successfully in C#?
a) Task.IsCompletedSuccessfully
b) Task.IsSuccessful
c) Task.Completed
d) Task.Status
Answer: a) Task.IsCompletedSuccessfully
Explanation: The Task.IsCompletedSuccessfully
property is used to check if a task has completed successfully without errors. It returns true
if the task has finished successfully, and false
if it was canceled or faulted. This helps in determining the final outcome of a task after it has completed.
158. Which of the following is an advantage of using
asynchronous programming in C#?
a) It guarantees that tasks will be completed in a specific
order.
b) It avoids blocking the calling thread, making the application more
responsive.
c) It automatically executes multiple tasks in parallel.
d) It uses more system resources than synchronous methods.
Answer: b) It avoids blocking the calling thread,
making the application more responsive.
Explanation: Asynchronous programming allows tasks to run without blocking the calling thread, which improves application responsiveness, especially in UI applications. It enables tasks like I/O operations to complete without freezing the user interface or affecting the application's performance.
159. What will the following C# code output?
var a = new[] { 1, 2, 3 };
var b = new[] { 1, 2, 3 };
Console.WriteLine(a.Equals(b));
a) true
b) false
c) NullReferenceException
d) Compilation error
Answer: b) false
Explanation: In C#, the Equals
method checks for reference equality by default, meaning it compares if both arrays point to the same memory location. Even though a
and b
contain the same elements, they are two separate array objects, so a.Equals(b)
returns false
. To compare array contents, you would use methods like SequenceEqual()
instead.
160. Which of the following C# features introduced in C#
8.0 helps improve code safety and eliminates null reference exceptions?
a) readonly
b) Pattern matching
c) Nullable reference types
d) async methods
Answer: c) Nullable reference types
Explanation: Introduced in C# 8.0, nullable reference types help improve code safety by distinguishing between reference types that can be null
and those that cannot. It provides compiler warnings when a nullable reference type is dereferenced without being checked for null
, effectively reducing the risk of null reference exceptions in code.
Comments
Post a Comment