0% found this document useful (0 votes)
8 views

Csharp - Collated - Updated

Uploaded by

Rohit Raj Verma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Csharp - Collated - Updated

Uploaded by

Rohit Raj Verma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 75

C# questions

1. Consider the following array:


Book[] bookArray = {
new Book() { Id = 1, Category = "Fiction", PubYear = 1997 },
new Book() { Id = 2, Category = "Bios & Memoirs", PubYear = 2015 },
new Book() { Id = 3, Category = "Business", PubYear = 2015 },
new Book() { Id = 4, Category = "Classics" , PubYear = 1962 },
new Book() { Id = 5, Category = "History" , PubYear = 2001 },
new Book() { Id = 6, Category = "Fiction", PubYear = 2001 },
new Book() { Id = 7, Category = "Bios & Memoirs",PubYear = 1997 }
};
You write the following Language-Integrated Query (LINQ) to sort these books by publication
year in descending order. If there are duplicate publication years, it should sort by category in
ascending order.
bookArray.OrderBy(x => x.PubYear).ThenBy(x => x.Category);
This does not produce the results you wanted, however. What is the correct way to do this?
 bookArray.OrderByDescending(x => x.PubYear)
.OrderByAscending(x => x.Category);
 bookArray.OrderByDescending(x => x.PubYear)
.ThenBy(x => x.Category);
 bookArray.OrderByDescending(x => x.PubYear)
.OrderBy(x => x.Category);
 bookArray.OrderByDescending(x => x.PubYear)
.ThenByAscending(x => x.Category);

2. What is the output of the following code?


int f = 0;
do {
Console.WriteLine(f);
f++;
}
while (f < 3);

f = 0;
while (f < 3) {
Console.WriteLine(f);
f++;
}
0
1
2
0

General Information
1
2
 0
1
2
1
2
3
 1
2
3
0
1
2
 0
1
2
3
0
1
2
3
 I don't know yet.

3. The following code defines a public delegate and the method it will call:
public delegate void delegateName(string message);
public static void delegateMethod(string message)
{
Console.WriteLine(message);
}
How would you call this delegate?
 Add a using statement for the delegate to the class level where your method exists and call the
delegate from a class level static method.
 Create a new instance of the delegate and call the delegate from a class level static method.
 Directly call the delegate.
 Instantiate the delegate and call the instance.
 I don't know yet.

4. Given the following declarations:


string[,] surnames1;
string[][] surnames2;

General Information
What is the difference between these two variables?
 surnames1 is a single dimension array, whereas surnames2 is a multidimensional array.
 surnames1 and surnames2 are the same functionally, but use different syntax.
 surnames1 is a jagged array and surnames2 is a multidimensional array.
 surnames1 is a reference to a multidimensional array and surnames2 is a reference to a jagged
array.
 I don't know yet.

5. What does the following code display?


public class Employee
{
public decimal Bonus { get { return 0m; } }
}

public class Manager : Employee


{
public new decimal Bonus { get { return 10000m; } }
}

Employee user1 = new Manager();


Console.WriteLine("${0}: {1}", user1.Bonus, user1.GetType().Name);
 $10000: Manager
 $0: Manager
 $10000: user1
 $0: user1
 I don't know yet.

6. Given the following record:


public record Hammer {
//code here
}
Which line of code results in a syntax error?
 Changing the Hammer record class to abstract:
public abstract record Hammer
 Changing the Hammer record class to inherit from a Tool record class:
public record Hammer : Tool
 Declaring the following constructor in the Hammer class:
public record Hammer(double val1, double val2);
 Declaring and initializing a Hammer record object:
record hammer = new Hammer();
 I don't know yet.

General Information
7. What is true about records?
 They are mutable by default
 They are immutable in positional syntax
 They cannot be inherited
 They cannot be declared abstract
 I don't know yet.

8. Consider the following code:


public interface RandomChoiceCollection<T>
{
T GetRandomItem();
}
How could you make the type parameter T covariant?
 Change the method signature to void GetRandomItem(in T).
 Change the interface type to RandomChoiceCollection<out T>.
 Change the interface type to RandomChoiceCollection<in T>.
 Change the method signature to out T GetRandomItem().
 I don't know yet.

9. You write a suitable type called Language with appropriate constructors and a Name property.
What is the output of the following code depending on its type?
Language x = new Language(Name: "C#");
Language y = x;
x.Name = "VB";
Console.WriteLine(y.Name);
 "VB" if Language is a struct
"C#" if Language is a class
 "C#" in all cases
 "C#" if Language is a struct
"VB" if Language is a class
 "VB" in all cases
 I don't know yet.

10. Given the following list of integers:


List<int> ages = new List<int> { 17, 21, 21, 46, 46, 55, 55, 55 };
How can you create a new collection of integers that contains no duplicate ages?
 List<int> newAges = ages.SelectMany().Distinct();
 List<int> newAges = ages.Distinct();
 IEnumerable<int> newAges = ages.Select().Distinct();

General Information
 IEnumerable<int> newAges = ages.Distinct();
 I don't know yet.

11. Which primitive type would be able to hold the number 55,000?
 short
 ushort
 byte
 sbyte
 I don't know yet.

12. The following declaration of a variable stores the current estimated value of distance between
two given objects:
public double estimatedDistance;
You create the following method to do some calculations and return a reference to this variable, but this
code results in a syntax error. How can you fix this?
public ref double GetEstimatedDistance() {
//do some calculations
return estimatedDistance;
}
 Add the ref keyword to the return statement in GetEstimatedDistance() and remove it from the
method declaration:
public double GetEstimatedDistance() {
return ref estimatedDistance;
}
 Change the return type of the method to void.
 Declare the estimatedDistance variable with the ref keyword:
public ref double estimatedDistance;
 Add the ref keyword to the return statement in GetEstimatedDistance():
return ref estimatedDistance;
 I don't know yet.

13. How does C# accomplish runtime polymorphism?


Through overriding

14. You created the following classes:


class OuterClass {
public int myInt;

class InnerClass {
InnerClass() { }
//other stuff

General Information
}
}

You try to increment the myInt variable in the InnerClass constructor but cannot. What can you change
to access that variable?
 Declare both InnerClass and OuterClass as public.
 Declare OuterClass as public.
 Pass OuterClass as an argument in the InnerClass constructor.
 Declare a second myInt variable in InnerClass and increment that one.
 I don't know yet.

15. The current date is November 25, 2025 and the current time is 1:00 PM. What will the
output to the console be once the following function executes?
private void PrintOutDateTime()
{
DateTime localDate = DateTime.Now;
var n = localDate.Month + 5;
var culture = new System.Globalization.CultureInfo("en-US");

//Line 1
Console.WriteLine(localDate.ToString(culture));
//Line 2
Console.WriteLine(localDate.ToString("M/d/yyyy"));
//Line 3
Console.WriteLine(n);
}

 11/25/25 1:00 PM 11/25/2025 April

 11/25/2025 1:00:00 PM
11/25/2025
16

 11/25/25 1:00 PM
11/25/2025
April

 Nov 25, 2025 01:00 PM


11/25/2025
April

General Information
16.What is wrong with the following code?
public abstract record Person {
public string FirstName { get; init; }
public string LastName { get; init; }
public Person(string firstName, string lastName)
=> (FirstName, LastName) = (firstName, lastName);
public void Deconstruct(out string firstName, out string lastName)
=> (firstName, lastName) = (FirstName, LastName);
}

public class Student : Person {


public double GPA { get; init; }
public string SchoolName { get; init; }
//other relevant code
public void Deconstruct(out double gpa, out string school)
=> (gpa, school) = (GPA, SchoolName);
}

 A class cannot inherit from a record

 Either both Person and Student must be declared as abstract or neither should be
 A base record and a sub record cannot both have a Deconstruct method
 A constructor is always required in a record class

17. There are multiple tasks from a single thread and you must propagate any exceptions
back to the calling thread, handling each exception individually. How can you do so?
 By catching System.AggregateException and iterating over its InnerExceptions collection
 By starting each task with the optional parameter of .wait() and logging exceptions before
continuing with the next task
 By catching Aggregate.TaskException and iterating over its InnerExceptions collection
 By wrapping the multiple tasks within a try/catch block, logging any errors, and
running continue() on the next task
 I don't know yet.

What does the following statement do?


using System;

General Information
 Imports the System.dll assembly and allows types in that assembly to be referenced without
specifying the namespace
 Allows types in the System namespace to be referenced without specifying the namespace
explicitly
 Imports the System.dll assembly, so that types in that assembly can be used
 Places the System library file in temporary memory
 I don't know yet.

Which code block correctly references this class and its static members with no syntax errors?
public class Bird
{
public static int NumberOfLegs = 2;
public static bool CanFly = true;

public static void BirdDescription()


{
// Do Something
}
}

Bird.BirdDescription();
int numLegs = Bird.NumberOfLegs;
bool canFly = Bird.CanFly;

var bird = new Bird();


int numLegs = bird.NumberOfLegs;
bool canFly = bird.CanFly;

var bird = new Bird();


bird.NumberOfLegs = 2;
bird.CanFly = true;

var bird = Bird.BirdDescription();


int numLegs = Bird.NumberOfLegs;
bool canFly = Bird.CanFly;

General Information
The following try/catch block results in the loss of the current stack trace, and a new stack trace is
started at the current method:
try {
//try statements
} catch (Exception e) {
throw e;
}
What change can you make to preserve the entire stack trace?
 Remove the e in the catch declaration:
catch (Exception) {
throw e;
}
 Remove the e in the throw statement:
catch (Exception e) {
throw;
}
 Add a finally statement to the end.
 Add a finally statement between the try and catch statements.
 I don't know yet.

1. What is the difference between these two code snippets?


var value1 = (MyClass)source;
and
var value2 = source as MyClass;

 If the conversion fails, then the first snippet sets value1 to null, but the second
snippet throws an exception.
 The first snippet only compiles if an explicit cast exists from the type of source to
MyClass, the second snippet requires an implicit cast to exist.
 If the conversion fails, then the first snippet throws an exception, but the
second snippet sets value2 to null.
 value1 is statically typed as MyClass, but value2 is dynamically typed at runtime
to the actual type of source refers to.
 I don't know yet.

2. An ErrorLog class contains the following member:

~ErrorLog()
{
CleanupResources();

General Information
}
When will this member be invoked?
 As soon as theErrorLog instance goes out of scope.
 At some undetermined time but not until after ALL ErrorLog instances that exist
in the app have fallen out of scope.
 Your choice: incorrect -During final cleanup just before the app or process being
executed closes.
 At some undetermined time after the ErrorLog instance has been marked for
garbage collection.
 I don't know yet.

3. What must be different between two overloads of a method?


 EITHER the number of parameters OR the type of at least one parameter
 EITHER the names of the method overloads OR their return types
 The names of the method overloads
 EITHER the number of parameters OR the return type of each method overload
 EITHER the number of parameters OR the type of at least one parameter OR the
return type of each method overload
 I don't know yet.

4. Which data type would normally be recommended to store monetary values intended to
be used in currency calculations?
 decimal
 float
 ulong
 double
 don't know yet.

5. Look at this event declaration:


public event EventHandler<OrderAddedEventArgs> AddOrder
{
add { /* What goes here? */ }
remove { /* ... */ }
}
 What should the code that replaces /* what goes here? */ d
 Determine whether each handler should be invoked each time the event is raised.
 Attach a handler to the event.
 Act as a default handler for the event.
 Construct and initialize the event.
 I don't know yet.

6. Which statement is true in regard to inheritance?

General Information
 Private members are visible only in a derived class if the derived class is nested
inside their base class.
 Static members are visible only in a derived class if the derived classes are nested
in their base class.
 Finalizer members are visible only in a derived class if the derived classes are
nested in their base class.
 Const members are visible only in a derived class if the derived classes are nested
in their base class.
 I don't know yet.

7. You have a function that makes use of the await operator because evaluation may have to
be suspended at some point to allow the operation to complete. How would you declare
this function for it to be valid?

 private static async Task<int> funcName()


 private await Task<int> funcName()
 private static await Task<int> funcName()
 private await async void FuncName()
 I don't know yet.

8. What does the [ServiceContract] attribute do in this Interface class?


using System.ServiceModel;
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
 This ServiceContractAttribute is applied to the ICalculator interface to enforce
implementation of all delegated methods.
 Incorrect -
[ServiceContract] is applied to the ICalculator for XML documentation.
 Your choice: correct -
This ServiceContractAttribute is applied to the ICalculator interface to define a
service contract.
 Incorrect -
This ServiceContractAttribute is applied to the ICalculator interface as an enforceable
interface.
 Incorrect -
I don't know yet.

General Information
9. Which LINQ method returns a Boolean value?
 Any()
 Count()
 NotNull()
 FirstOrDefault()
 I don't know yet.

10. Consider the following XML snippet:


<!-- CustomersOrders.xml -->
<Customers>
<Customer CustomerID="GREAL">
<CompanyName>Great Lakes Food Market</CompanyName>
<ContactName>User One</ContactName>
</Customer>
<Customers>
Which Language Integrated Query (LINQ) would project an anonymous type?

 XElement custOrd = XElement.Load("CustomersOrders.xml");


var custList =
from el in custOrd.Element("Customers").Elements("Customer");

 XElement custOrd = XElement.Load("CustomersOrders.xml");


var custList =
from el in custOrd.Element("Customers").Elements("Customer")
select new
{
CustomerID = (string)el.Attribute("CustomerID"),
CompanyName = (string)el.Element("CompanyName")
};

 XElement custOrd = XElement.Load("CustomersOrders.xml");


var custList =
from el in custOrd.Element("Customers").Elements("Customer")
select el.Customers;

 XElement custOrd = XElement.Load("CustomersOrders.xml");


var custList =
from el in custOrd.Element("Customers").Elements("Customer")
select new Customer();

 I don't know yet.

11. Given the following dictionary, which statement would you use to find the value of the
element with the key value of "NV"?

General Information
IDictionary<string, string> states =
new Dictionary<string, string>();

states.Add("NY", "New York");


states.Add("FL", "Florida");
states.Add("CA", "California");
states.Add("NV", "Nevada");
 string value = string.Empty;
foreach( var s in states)
{
if (s.Value("NV", out value))
{
// do action
}
}
 string value = string.Empty;
foreach( var s in states)
{
if (s.Exists(s.Key, "NV"))
{
// do action
}
}

 string value = string.Empty;


if (states.TryGetValue("NV", out value))
{
// do action
}
 string value = string.Empty;
foreach( var s in states)
{
if (s.Compare(s.Key, "NV"))
{
// do action
}
}
 I don't know yet.

12. Which loop statement will produce a value of 25 in the Console.WriteLine() statement at
the bottom?

 int x = 1;
while (x <= 25)

General Information
{
x++;
}
Console.WriteLine("x: " + x);
 int x = 1;
while (x <= 25)
{
x++;
}
Console.WriteLine("x: " + x);
 int x = 1;
do
{
x++;
} while (x < 25);
Console.WriteLine("x: " + x);
 int x;
while (x == 0 || x < 26)
{
x++;
}
Console.WriteLine("x: " + x);
 I don't know yet.

13. How do you declare a generic method called Test that takes one parameter which must be
a value type?
 public void Test<T : struct>(T t)
{ /* ... */ }
 public void Test<T>(T t) where : T is struct
{ /* ... */ }
 public void Test<struct T>(T t)
{ /* ... */ }
 public void Test<T>(T t) where T : struct
{ /* ... */ }
 I don't know yet.
14. Given these two method overloads:
public static class NumberWriter
{
public static void Display(int x)
{
Console.WriteLine("Integer: " + x);
}
public static void Display(long x)
{

General Information
Console.WriteLine("Long: " + x);
}
}
What will the following code do?
short value = 10;
NumberWriter.Display(value);
 It will throw a RuntimeBinderException because the call to Display is ambiguous.
 It won't compile because the call to Display is ambiguous.
 It will display Long: 10.
 It will display Integer: 10.
 I don't know yet.

15. Which statement accurately describes the Language Integrated Query (LINQ) extension method
Union()?
 Union() returns all the values from two collections.
 Union() returns all values from a collection and distinct values from a second collection.
 Union() returns all values from one collection not found in a second collection.
 Union() returns values from two collections, excluding duplicates.
 I don't know yet.

16. Consider the following code: Order newOrder = new Order() {PartId="Ms23-49"}; What must the
Order class contain for this code to compile?
 An attribute that takes a string parameter called PartId
 A constructor that takes a string parameter called PartId and an attribute that allows a
string property called PartId to be set
 A constructor that takes a string parameter called PartId
 A default constructor (either explicit or compiler-generated) and a writeable string
property called PartId
 I don't know yet.

17. Consider the following array, Language Integrated Query (LINQ) query, and result:
// Array
List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };

// LINQ Query
var distinctAges = ages.Distinct();

// query result
distinctAges = {21, 46, 55, 17};
What change must you make to the LINQ query to return the average of the distinct values?

General Information
 Replace Distinct() with AverageDistinct()
 Change Distinct() to Select(x => x.Distinct).Average()
 Add the Average() extension method after Distinct()
 Change Distinct() to Average(x => x.Distinct)
 I don't know yet.

18. Consider this snippet of code:


PetOwner[] petOwners = {
new PetOwner { Name="Higa",
Pets = new List<string>{ "Scruffy", "Sam" } },
new PetOwner { Name="Hines",
Pets = new List<string>{ "Dusty" } }
};

// Project the pet owner's name and the pet's name.


var query = petOwners.SelectMany(petOwner => petOwner.Pets,
(petOwner, petName) => new { petOwner, petName })
.Select(ownerAndPet =>
new
{
Owner = ownerAndPet.petOwner.Name,
Pet = ownerAndPet.petName
}
);
Which statement correctly describes the functionality of the .SelectMany() clause in this
Language Integrated Query (LINQ)?

 SelectMany() uses on-demand, real-time execution to return values as objects from the
petOwners array.
 SelectMany() projects the first and last element of a sequence.
 SelectMany() enables the LINQ query to return the result set without the need for
enumeration such as foreach in C#.
 SelectMany() returns a flattened projection of the array petOwners.
 I don't know yet.

19. What is the visibility of the currentSpeed variable in the following code? public class Automobile
{
double currentSpeed {get; set;}
}

General Information
 public
 protected
 private
 internal
 I don't know yet.

20. The following code results in a compilation error. What must you change to correct this error?
public class TestAction1
{
public static void Main()
{
Action<T> messageTarget;
if (Environment.GetCommandLineArgs().Length >
messageTarget = ShowWindowsMessage;
else
messageTarget = Console.WriteLine;

messageTarget("Hello, World!");
}
private static void ShowWindowsMessage(string message)
{
MessageBox.Show(message);
}
}

 Replace Action<T> messageTarget with Func<bool> messageTarget.


 Replace Action<T> messageTarget with Action<string> messageTarget.
 Replace private static void ShowWindowsMessage(string message) with
 private Action<void> ShowWindowsMessage(string message).
 Replace private static void ShowWindowsMessage(string message) with private string
ShowWindowsMessage(string message).
 I don't know yet.

21. Why will the following code not compile?


interface Interface1 {
private record xxx;
private static void display1(int i) { }
public static string display1() {
return "";
}
}

General Information
public class MyClass {
public static void Main(string[] args) {
Interface1 inti = new Interface1();
//more implementation
}
}

 A record cannot be declared in an interface


 An interface cannot be instantiated
 An interface cannot have a private static method inside of it
 An interface method cannot have a body like it does in the second display1() method
 I don't know yet.

22. The following code segment is an example of what technique?


public static void Main()
{
OutputTarget output = new OutputTarget();
Func<bool> methodCall = delegate() { return output.SendToFile(); };
if (methodCall())
Console.WriteLine("Success!");
else
Console.WriteLine("File write operation failed.");
}
 Using the Func<TResult> delegate with dynamic methods
 the Func<TResult> delegate with lambda expressions
 Using the Func<TResult> function with public methods
 Using the Func<TResult> delegate with anonymous methods
 I don't know yet.

23. You have a record named Person


public record Person {
//properties here
}
How can you create a derived record type named Student that allows no further inheritance?

 public final record Student : Person { }


 private record Student : Person { }
 private sealed record Student : Person { }
 public sealed record Student : Person { }
 I don't know yet.

General Information
24. A unit test must have full control of the system it is testing. This can be problematic when the
production code includes calls to static references such as DateTime.Now. Which approach
resolves these challenges?
 Create unique stubs for all class methods requiring tests.
 Write mock methods controlled with a library and have the production code depend on
that interface.
 Extend all methods that you must control with an interface.
 Define an interface that can be mocked and have the production code depend on that
interface.
 I don't know yet.

25. What type of key is being used in this Language Integrated Query (LINQ) to join the data from
three tables?
var query = from o in db.Orders
from p in db.Products
join d in db.OrderDetails
on new {o.OrderID, p.ProductID} equals new {d.OrderID, d.ProductID} into details
from d in details
select new {o.OrderID, p.ProductID, d.UnitPrice};
 Multi key
 Primary key
 Unique key
 Composite key
 I don't know yet.

26. Which is an example of a base class that you can reuse?


 private static int GetNumber();
 System.Windows.Forms.Button
 interface IInterface
 sealed class myClassA : myClassB
 I don't know yet.

27. If arr is an array of int, how can you obtain the number of elements in arr?
 arr.Length
 arr.Length()
 arr.Count
 arr.Size()
 I don't know yet.

General Information
28. You wrote a class MyClass that overrides a base class method virtual void DoSomething(). How
can you prevent the MyClass override of DoSomething from being further overridden?
 Declare the method as private override in MyClass.
 Declare the method as public override in MyClass.
 Declare the method DoSomething as sealed override.
 Declare the method as public virtual sealed in MyClass.
 I don't know yet.

29. Which Threading.Task method will create a task that will complete when any of the associated
tasks have completed?
 Task.GetAwaiter()
 Task.FromResult()
 Task.WhenAny()
 Task.WhenAll()
 I don't know yet.

30. Consider the following scenario:


 There are two classes: ClassA and ClassB
 ClassB is only useful to ClassA
What is the best way to ensure that only ClassA can use ClassB?
 Make ClassB a private nested class of ClassA.
 Make ClassB an inherited class of ClassA.
 Change ClassB to an interface and extend with ClassA.
 Use extend to expose ClassB to only ClassA.
 I don't know yet.

31. What is the main purpose of an extension method?


 To add functionality to an existing type without directly modifying that type
 To add additional behavior to an existing method
 To protect the level of security on some of the methods in the extended class
 To add functionality to a derived class not available in its base class
 I don't know yet.

32. Which statement accurately describes an event?


In the .NET Framework class library, events are based on the System.Events delegate and the
System.Args base class.

General Information
 An event allows a single subscriber, but the subscriber can handle multiple events from
multiple publishers.
 The publisher determines when an event is raised; the subscribers determine what
action is taken in response to the event.
 When an event has multiple subscribers, the event handlers are always invoked
asynchronously when an event is raised.
 I don't know yet.

33. The following try/catch block results in the loss of the current stack trace, and a new stack trace
is started at the current method:
try {
//try statements
} catch (Exception e) {
throw e;
}
What change can you make to preserve the entire stack trace?
 Add a finally statement between the try and catch statements.
 Remove the e in the throw statement:
catch (Exception e) {
throw;
}
 Remove the e in the catch declaration:
catch (Exception) {
throw e;
}
 Add a finally statement to the end.
 I don't know yet.

34. What is the output of the following code?


int ab = 1;
Console.WriteLine(ab);
Console.WriteLine(++ab);
Console.WriteLine(ab++);
Console.WriteLine(ab--);
Console.WriteLine(--ab);
 1
1
2
3
2

General Information
 1
1
2
3
3

 1
2
2
3
1

 1
2
3
2
1

 I don't know yet.

35. The following lines of code are declarations of the same multidimensional array (arr):
// Declaration 1
int[,] arr = new int[,] { { 1, 2 }, { 3, 4 } };
// Declaration 2
int[,] arr = new int[2, 2] { { 1, 2 }, { 3, 4 } };
Which statement accurately describes the difference between these two declarations?
 Declaration 1 implicitly sets the dimensions of the array and Declaration 2 explicitly
sets the dimensions of the array.
 Declaration 1 defines the fixed size of the array while the size of the Declaration 2 array
can expand at run-time.
 Declaration 1 explicitly sets the dimensions of the array and Declaration 2 implicitly sets
the array dimensions.
 Declaration 1 allows the size of the array to be changed at run-time and Declaration 2
explicitly sets the dimensions of a jagged array.
 I don't know yet.

36. What does the Deconstruct method do for a record?


 It makes properties accessible, even if the record is marked as private.

General Information
 It can encapsulate properties in the record.
 It can extract properties from the record.
 It makes properties accessible, even if the record is marked as sealed.
 I don't know yet.
37. What change can you make to the following abstract class to eliminate the syntax error?
 Remove the line of code inside the eatFood() method.
 Add a method body to the makeSound() method.
 Add a method body to the sleep() method.
 Update the isSleeping() method to either public or private.
 I don't know yet.

38. What will the value of fact2 be after this code executes?
string fact = "Life is too short to...always remove the USB drive safely";

int start = fact.IndexOf("always");

var fact2 = fact.Substring(start);


 always
 remove the USB drive safely
 Life is too short to...
 always remove the USB drive safely
 I don't know yet.

39. Which statement is true about delegates?


 Delegates cannot be chained together.
 The delegate type and methods type must match exactly.
 Delegates allow methods to be passed as parameters.
 The delegate must be instantiated with a method or lambda expression.
 I don't know yet.

40. The following code results in a compilation error. What must you change to correct this error?
public class TestAction1
{
public static void Main()
{
Action<T> messageTarget;
if (Environment.GetCommandLineArgs().Length > 1
messageTarget = ShowWindowsMessage;
else
messageTarget = Console.WriteLine;

General Information
messageTarget("Hello, World!");
}
private static void ShowWindowsMessage(string message)
{
MessageBox.Show(message);
}
}

1.

You have the following record declaration and implementation:


record DailyTemperature(double high, double low);

class MyClass {
private static DailyTemperature[] tempData = new DailyTemperature[] {
new DailyTemperature(high: 57, low: 30),
new DailyTemperature(60, 35),
new DailyTemperature(63, 33)
};
public static void Main(string[] args) {
tempData[1].high = 30;
}
}
Why won't this code compile?

tempData[1].high is immutable, so it can only be set at object initialization, not in


the main method.

2. Which primitive type would be able to hold the number 55,000?

Unshort

3. There are multiple tasks from a single thread and you must propagate any exceptions back to
the calling thread, handling each exception individually. How can you do so?

By catching System.AggregateException and iterating over its InnerExceptions collection

General Information
4. You created the following positional record:
public record Person(string FirstName, string LastName);
Given this positional record, how can you construct a new Person?

var person = new Person("First", "Last");

5. How many times does the first statement (int i = 0;) of this for loop execute?
for (int i = 0; i < 5; i++) {
//do stuff
}

6.

You have the following declaration of a Person record:


public record Person {
public string FirstName { get; init; }
public string LastName { get; init; }
public Person(string firstName, string lastName)
=> (FirstName, LastName) = (firstName, lastName);
public void Deconstruct(out string firstName, out string lastName)
=> (firstName, lastName) = (FirstName, LastName);
What change can you make to show the exact same Person record with shorter syntax?

Use the following positional record instead:


public record Person(string FirstName, string LastName);

7.

Which statement accurately describes an event?

General Information
 The publisher determines when an event is raised; the subscribers determine what action
is taken in response to the event.

8.

What does the following statement do?


using System;

Allows types in the System namespace to be referenced without specifying the namespace
explicitly

9.

What is the relationship between String and string in C#?

string is an alias of String.

10.

The following try/catch block results in the loss of the current stack trace, and a new stack trace
is started at the current method:
try {
//try statements
} catch (Exception e) {
throw e;
}
What change can you make to preserve the entire stack trace?

Remove the e in the throw statement:


catch (Exception e) {
throw;
}

11.

The following code segment is an example of what technique?


public static void Main()
{
OutputTarget output = new OutputTarget();
Func<bool> methodCall = delegate() { return output.SendToFile(); };
if (methodCall())

General Information
Console.WriteLine("Success!");
else
Console.WriteLine("File write operation failed.");
}

Using the Func<TResult> delegate with anonymous methods

12.

You have a record named Person.


public record Person {
//properties here
}
How can you create a derived record type named Student that allows no further inheritance?

public sealed record Student : Person { }

13.

The following array specifies a programmer's skillset:


string[] skillSet = {"C#","Asp","MVC","Linq","Entity","Jquery","Sql"};
You want to convert this list into a comma separated string and print it out by doing the
following:
Console.WriteLine(skillSet.Join((s1, s2) => s1 + ", " + s2));
This results in a syntax error. What change can you make to successfully print out this list?

Change the Join function to Aggregate.

14.

How would you use XML documentation for the following attributes?

 parameter: named intX with description of "number to be squared"


 summary: Returns the squared value of an integer value

General Information
 /// <summary>
/// Returns the squared value of an integer value
/// </summary>
/// <param name="intX">number to be squared</param>

15.

You can create a record as a reference type instead of which other construct?

Classes and structs

16.

Consider the following DateTime variable:


DateTime dteToFormat = new DateTime(2025,12,30);
How should you return a second value using dteToFormat to change the format from
"12/30/2025" to "Dec 30, 2025"?

By using DateTime string formatting methods and another variable

string formattedDate = dteToFormat.ToString("MMM dd, yyyy");

17.

Consider this method where orderProcessor is not a null value:

static void SetupHandler(OrderProcessor orderProcessor)


{
string itemName = "Pluralsight Subscription";
// AddOrder is an event
orderProcessor.AddOrder += (sender, e) => Console.WriteLine("Item: " + itemName);
}

What will happen when the AddOrder event is subsequently raised?

The console will display the following:


Item: Pluralsight Subscription

18.

General Information
In this code example, what type of class is Student?
class Class {
private List<Student> _students = new List<Student>();

public void AddOrderLine(string name, double grade){


Student student = new Student();
student.Name = name;
student.Grade = grade;
student.PassClass = _students.passClass(grade);
}

public double OrderTotal() {


double total = 0;

foreach (OrderLine line in _orderLines) {


total += line.OrderLineTotal();
}

return total;
}

private class Student {


public string Name { get; set; }
public double Grade { get; set; }
public bool PassClass { get; set; }

public bool passClass(){


return Grade <= 59 ? false : true;
}
}
}

nested

19.

What is accurate regarding class inheritance?

A derived class is the class that inherits from another class and a base class is the class being
inherited from.

20.

General Information
What is a difference between an interface and an abstract class?

An abstract class can contain a constructor, whereas an interface cannot.

What does the [ServiceContract] attribute do in this Interface class?


using System.ServiceModel;
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
 This ServiceContractAttribute is applied to the ICalculator interface to define a service contract.
 This ServiceContractAttribute is applied to the ICalculator interface to enforce implementation
of all delegated methods.
 This ServiceContractAttribute is applied to the ICalculator interface as an enforceable interface.
 [ServiceContract] is applied to the ICalculator for XML documentation.
 I don't know yet.

What does the Deconstruct method do for a record?


 It makes properties accessible, even if the record is marked as sealed.
 It can extract properties from the record.
 It makes properties accessible, even if the record is marked as private.
 It can encapsulate properties in the record.
 I don't know yet.

What is the difference between the behavior of the following two pieces of code?
catch(Exception e)
{
throw;
}
and
catch(Exception e)
{
throw e;
}
 throw creates a new exception instance, whereas throw e reuses e.
 throw reuses e, whereas throw e creates a new exception instance.

General Information
 throw does not preserve the stack trace of the originating exception, whereas throw e does.
 throw preserves the stack trace of the originating exception, whereas throw e does not.
 I don't know yet.

What can an abstract class have that an interface cannot?


 Events and indexers
 An instance constructor
 Multiple class inheritance
 Private methods
 I don't know yet.

In C#, which kind of members are forbidden in an interface?


 Events
 Instance fields
 Nested types
 Constants
 I don't know yet.

You wrote a class called EmployeeList that encapsulates a list of Employee instances. You want to write
an indexer to obtain an Employee instance from the list by specifying the integer index of the required
employee. What is the correct syntax for declaring the indexer?
 public Employee this [int index] { ... }
 public Employee operator [] (int index) { ... }
 public Employee this[] (int index) { ... }
 public static Employee operator [] (int index) { ... }
 I don't know yet.

Which list type can store a simple list of delegates?


 HandledEventHandler
 EventHandlerList
 HandledEventArgs
 List<T(Delegate)>
 I don't know yet.

What is the output of the following code?


string greet = "Hello";
string copy = greet;
greet = "World";

General Information
bool test = Object.ReferenceEquals(greet,copy);
Console.WriteLine ($"{copy} {test}");
 Hello True
 World False
 Hello False
 World True
 I don't know yet.

What change can you make to remove the syntax error in the following class?
public class Car {
private static int numWheels;
private string type;

static Car(string _type) {


numWheels = 4;
type = _type;
}

public Car(string _type) {


numWheels = 4;
type = _type;
}
}
 Make type a static variable.
 Remove the parameter from the first constructor and its type assignment.
 Remove the second constructor.
 Remove the parameter from the second constructor and its type assignment.
 I don't know yet.

Which change would you apply to the following interface to remove the syntax error?
interface Interface1 {
private record iRecord;
private static void display1(int i) { }
public static string display1() {
return "";
}
public abstract void display2() { }
}
 Delete the iRecord.
 Remove the method body of the display2() method and replace it with a semicolon.
 Remove the line of code inside the second display1() method.
 Rename the first display1() method to something unique.
 I don't know yet.

General Information
You created a positional record as follows:
public record Person(string FirstName, string LastName);
How can you invoke a positional deconstructor on this record?
 record person = new Person();
 var (p, l) = person;
 var person = new Person("User", "One");
 var person(p, l);
 I don't know yet.

Which statement accurately describes the properties of the following array?


string[] arr = new string[5];
 The array is declared but not initialized and contains no elements.
 The array is declared, not initialized and contains five elements with null values.
 The array is declared and initialized and contains five elements with string.Empty values.
 The array is declared and initialized and contains elements set to null.
 I don't know yet.

You must cancel a Threading.Task that is running. From which class should you call its
associated Cancel method to do this?
 System.Threading.CancellationTokenRegistration
 System.Threading.Tasks.Task
 System.Threading.CancellationTokenSource
 System.Threading.Tasks.TaskCanceledException
 I don't know yet.

What sequence of characters indicates the start of an XML-style documentation comment in C# code?
 ///
 <!--
 //
 /*
 I don't know yet.

Given these two method overloads:


public static class NumberWriter
{
public static void Display(int x)
{
Console.WriteLine("Integer: " + x);
}

General Information
public static void Display(long x)
{
Console.WriteLine("Long: " + x);
}
}
What will the following code do?
short value = 10;
NumberWriter.Display(value);
 Not compile because the call to Display is ambiguous.
 Display Integer: 10.
 Throw a RuntimeBinderException because the call to Display is ambiguous.
 Display Long: 10.
 I don't know yet.

When would you use the yield break statement?


 When you must transfer an async method back to the original thread
 When you must end a while or do while loop early
 When you must return a value from inside a catch block
 When an iterator comes to an end
 I don't know yet.

The following code results in a compilation error. What must you change to correct this error?
public class TestAction1
{
public static void Main()
{
Action<T> messageTarget;
if (Environment.GetCommandLineArgs().Length > 1)
messageTarget = ShowWindowsMessage;
else
messageTarget = Console.WriteLine;

messageTarget("Hello, World!");
}
private static void ShowWindowsMessage(string message)
{
MessageBox.Show(message);
}
}
 Replace Action<T> messageTarget with Action<string> messageTarget.
 Replace private static void ShowWindowsMessage(string message) with
private Action<void> ShowWindowsMessage(string message).
 Replace private static void ShowWindowsMessage(string message) with private string
ShowWindowsMessage(string message).
 Replace Action<T> messageTarget with Func<bool> messageTarget.
 I don't know yet.

General Information
What must x satisfy if this code is to compile?

lock (x)
{
SaveChanges();
}
 It must be of type Monitor or Mutex.
 It must be an instance of a reference type.
 It must be an instance class member.
 It must implement IDisposable.
 I don't know yet.

When looking for an item in a List, which method would result in a syntax error?
 BinarySearch
 Search
 Contains
 Find
 I don't know yet.

You have the following record declaration and implementation:


record DailyTemperature(double high, double low);

class MyClass {
private static DailyTemperature[] tempData = new DailyTemperature[] {
new DailyTemperature(high: 57, low: 30),
new DailyTemperature(60, 35),
new DailyTemperature(63, 33)
};
public static void Main(string[] args) {
tempData[1].high = 30;
}
}

Why won't this code compile?

 The DailyTemperature record is not declared correctly.


 DailyTemperature cannot be declared as static.

General Information
 tempData[1].high is immutable, so it can only be set at object initialization, not in
the main method.

 tempData must be initialized inside the main method.


 I don't know yet.

Given the following classes:


public class Person {
public virtual void DoSomething() {
Console.WriteLine("Person doing something.");
}
}
public class Employee : Person {
public override void DoSomething() {
Console.WriteLine("Student doing something.");
}
}
...
//main method
Employee emp = new Employee();
emp.DoSomething();
You expect the main method to print out the following two lines of output, but only the first line
prints out to your console.
Student doing something.
Person doing something.
What change to the Person or Employee class will result in both lines printing out?
 Add the following line of code at the end of DoSomething() in the Employee class:
base.DoSomething();
 Add the following line of code at the end of DoSomething() in the Person class:
base.DoSomething();
 Remove the virtual keyword to DoSomething() in the Person class.
 Remove the override keyword to DoSomething() in the Employee class.
 I don't know yet.

Review the following class Automobile:


public class Automobile
{
private static int CarId;
protected Drawing.Color AutoColor;

Automobile(int carId, Drawing.Color color)


{
CarId = carId;
AutoColor= color;

General Information
}
}
Which class correctly demonstrates a class inheriting the class Automobile?
 public class Car : Automobile(1, Color.Red)
{

}
 public class Car : Automobile()
{
private Automobile auto = new Automobile(1, Color.Red);
}
 public class Car : Automobile
{

}
 public class Car
{
private Automobile auto = new Automobile(1, Color.Red);
}
 I don't know yet.

Which keyword would you use to pass a value-type instance by reference in a method?
 ByReference
 ByRef
 ref
 reference
 I don't know yet.

You use an interface named IService to inject different implementations into a system. When the
following code is compiled an error is returned, however.
1. public interface IService<T> { }
2. public class ServiceA : IService<int> {}
3. public class ServiceB : IService<String> {}
4. public class ServiceC : IService<>() {}
Which line is the cause of the error?
 3
 4
 1
 2

Consider the following method:


string _firstName = string.Empty;
string _lastName = string.Empty;

public void ConcatName(){

General Information
return _firstName + " " + _lastName;
}
When this code is compiled there is an error. What must be changed to correct this problem?
 Add _firstName and _lastName as parameters for the method
 Change the access level from public to private
 Return the value using get; and set;
 Change the return type from void to string
 I don't know yet.

How can you make code reusable?


 Using databases
 Using interfaces
 Using properties
 Using constructors
 I don't know yet.

What will the output be after this switch statement executes?


int caseSwitch = 1;

switch (caseSwitch){
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
default:
Console.WriteLine("Case default");
break;
}
 Case 3
 Case 2
 Case 1
 Case default
 I don't know yet.

What is a constructor?
 A method for initializing an interface or an abstract class
 A special reference to a group of constants
 A field or method inside a class
 A method for initializing an object
 I don't know yet.

General Information
Which component of a C# application acts as the entry point?
 The class declaration
 The declaration of namespace
 The Main method
 The first class instantiation
 I don't know yet.

Which operator will increment an integer by a value of 1?


 +
 !=
 ++
 =+
 I don't know yet.

Which keyword would you use to import a namespace into a C# application?


 use
 import
 using
 define
 I don't know yet.

Consider the following array:


Book[] bookArray = {
new Book() { Id = 1, Category = "Fiction", PubYear = 1997 },
new Book() { Id = 2, Category = "Bios & Memoirs", PubYear = 2015 },
new Book() { Id = 3, Category = "Business", PubYear = 2015 },
new Book() { Id = 4, Category = "Classics" , PubYear = 1962 },
new Book() { Id = 5, Category = "History" , PubYear = 2001 },
new Book() { Id = 6, Category = "Fiction", PubYear = 2001 },
new Book() { Id = 7, Category = "Bios & Memoirs",PubYear = 1997 }
};
You must provide a list (List<T>) of books from the bookArray that were published before 2000.
Which LINQ query will produce the correct result set?
 var books = (from b in bookArray
where b.PubYear <= 2000
select b).ToList();
 var books = (from b in bookArray
where b.PubYear < 2000
select b).ToArray();
 var books = (from b in bookArray
where b.PubYear < 2000
select b).ToList();
 var books = from b in bookArray
where b.PubYear < 2000
select b
 I don't know yet.

General Information
You are creating a program that generates a random number between 1 and 10 as follows:
int num = new Random().Next(1, 11);
The output displays the class of the number based on the following criteria:
- Less than 3: Low number
- Between 3 and 6: Middle number
- Between 7 and 9: High number
- 10: 10
How would the associated if statement look for this criteria?
 if (num <= 3)
Console.WriteLine("Low number");
else if (num >= 3 || num <= 6)
Console.WriteLine("Middle number");
else if (num > 6 || num < 10)
Console.WriteLine("High number");
else
Console.WriteLine("10");
 if (num <= 3)
Console.WriteLine("Low number");
else if (num == 3 || num <= 7)
Console.WriteLine("Middle number");
else if (num == 8 || num < 10)
Console.WriteLine("High number");
else
Console.WriteLine("10");
 if (num < 3)
Console.WriteLine("Low number");
else if (num >= 3 && num <= 6)
Console.WriteLine("Middle number");
else if (num > 6 && num < 10)
Console.WriteLine("High number");
else
Console.WriteLine("10");
 if (num < 3)
Console.WriteLine("Low number");
else if (num > 3 && num < 6)
Console.WriteLine("Middle number");
else if (num >= 6 && num <= 10)
Console.WriteLine("High number");
else
Console.WriteLine("10");
 I don't know yet.

Which of these is considered an advantage of object-oriented programming?


 Code maintainability
 Security
 Error handling
 Faster compile time
 I don't know yet.

General Information
What will be the results of the following expression if zero is an int and contains the value 0?
int zero = 0;
int x = 100 / zero;
 It will throw DivideByZeroException.
 It will return int.PositiveInfinity.
 It will return int.NaN.
 It will throw an unknown error exception.
 I don't know yet.
Which keyword would you use to create an object?
 class
 new
 create
 var
 I don't know yet.
Assuming today's date is January 1, 2025, what will the following format return?
string formattedDate = DateTime.Now.ToString("dddd, dd MMMM");
 Wednesday, 01 January
 Wed, 01 Jan
 Wednesday, 1 Jan
 3, 01 01
 I don't know yet.

A try block surrounds a block of your code. You must run a few lines of code to close some
streams and database calls whether an exception is thrown or not. How can you ensure that this
code runs?
 Add a break statement at the end of the try block.
 Add a finally block between the try and catch block.
 Add a break statement at the end of the catch block.
 Add a finally block after the catch block.
 I don't know yet.

Consider the following interfaces and class that implements both interface I1 and I2:
interface I1
{
void A();
}

interface I2
{
void A();
}

class C : I1, I2
{
public void A()
{
Console.WriteLine("C.A()");

General Information
}
}
Which statement is true regarding A()?
 A() can only be invoked through the I1 or I2 interfaces explicitly.
 A() is a public class member that implicitly implements a member of both
interfaces.
 A() is a public class member that explicitly implements a member of both
interfaces.
 A() can be invoked only through the class itself.
 I don't know yet.

What does ~0 (the number zero with a tilde symbol in front of it) evaluate as?
 int.MaxValue
 -1
 255
 True
 I don't know yet.

What can you use to simulate inheritance for a struct?


 An interface
 An abstract class
 A protected class
 A parent struct
 I don't know yet.

If you define a class or struct, C# sometimes provides a default parameterless constructor. When
does this happen?
 Whenever the class or struct does not define a parameterless constructor
explicitly
 Only if no constructors are explicitly defined
 Always for a struct; for a class, only if no constructors are explicitly defined
 Only for structs, never for classes
 I don't know yet.

Which type of access modifier for a field results in a syntax error?


 protected internal string str1;
 static readonly string str1;
 readonly ref string str1;
 private protected string str1;
 I don't know yet.

How would you remove the third element in the following array?

General Information
Book[] bookArray = {
new Book() { Id = 1, Category = "Fiction", PubYear = 1997 },
new Book() { Id = 2, Category = "Bios & Memoirs", PubYear = 2015 },
new Book() { Id = 3, Category = "Business", PubYear = 2015 },
new Book() { Id = 4, Category = "Classics" , PubYear = 1962 },
new Book() { Id = 5, Category = "History" , PubYear = 2001 },
new Book() { Id = 6, Category = "Fiction", PubYear = 2001 },
new Book() { Id = 7, Category = "Bios & Memoirs", PubYear = 1997 }
};
 bookArray.RemoveAt(2);
 bookArray = bookArray.Where((source, index) => index != 2).ToArray();
 bookArray.RemoveAt(3);
 int posToRemove = 2;
for (int i = posToRemove - 1; i < bookArray.Length-1; i++) {
bookArray[i] = bookArray[i + 1];
}
 I don't know yet.

Which types of parameters support covariance and contravariance to provide greater flexibility in
assigning and using generic types?
 Generic interfaces, delegates, and classes
 Generic interfaces and delegates
 Generic interfaces, classes, and structs
 Generic classes and structs
 I don't know yet.

Which method finds the difference in days as an integer between two dates?
 var numOfDays = DateTime.DateDiff(date1,date2,Days);
 var numOfDays = date1.Subtract(date2).Days;
 var numOfDays = (date1 - date2).TotalDays;
 var numOfDays = DateTime.Subtract(date1,date2,Days);
 I don't know yet.

Which statement is true regarding the Main method?


 It can have private access.
 The return type is limited to void and int.
 If the return type is int, it can include the async modifier.
 The string[] parameter is required.
 I don't know yet.

What will be the output of the following code?


public record Person {
public string FirstName { get; init; }
public string LastName { get; init; }
}
public class MyClass {
public static void Main(string[] args) {
var personx = new Person { FirstName = "First", LastName = "Last" };

General Information
var persony = new Person { FirstName = "First", LastName = "Last" };
if (personx == persony)
System.Diagnostics.Debug.WriteLine("equal");
else
System.Diagnostics.Debug.WriteLine("not equal");
if (personx.Equals(persony))
System.Diagnostics.Debug.WriteLine("equal");
else
System.Diagnostics.Debug.WriteLine("not equal");
}
}
 not equal
not equal
 equal
not equal
 not equal
equal
 equal
equal
 I don't know yet.

You have two types, ClassA and ClassB. Inside which types could you define a custom implicit
type conversion from ClassA to ClassB?
 ClassA or ClassB
 ClassA or ClassB or any class that inherits from either ClassA or ClassB
 ClassA or any class that inherits from A
 Only ClassA
 I don't know yet.

The following array consists of seven elements:


Book[] bookArray = {
new Book() { Id = 1, Category = "Fiction", PubYear = 1997 },
new Book() { Id = 2, Category = "Bios & Memoirs", PubYear = 2015 },
new Book() { Id = 3, Category = "Business", PubYear = 2015 },
new Book() { Id = 4, Category = "Classics" , PubYear = 1962 },
new Book() { Id = 5, Category = "History" , PubYear = 2001 },
new Book() { Id = 6, Category = "Fiction", PubYear = 2001 },
new Book() { Id = 7, Category = "Bios & Memoirs",PubYear = 1997 }
};
You receive two new nonfiction books and want to add them to the array. You do the following:
Book book = new() { Id = 8, Category = "Nonfiction", PubYear = 2020 };
Book book2 = new() { Id = 9, Category = "Nonfiction", PubYear = 2021 };
Console.WriteLine("bookArray count is " + bookArray.Length);
bookArray.Append(book);
bookArray.Append(book2);
Console.WriteLine("bookArray count is " + bookArray.Length);
Both statements print out "bookArray count is 7". How can you change this to successfully add
these two new books?
 Use the Add() method instead:

General Information
bookArray.Add(book);
bookArray.Add(book2);
 Resize the array before adding the new books:
Array.Resize(ref bookArray, bookArray.Length + 2);
 Resize the array before adding the new books:
bookArray.Resize(bookArray.Length + 2);
 Use the AddRange() method instead:
bookArray.AddRange(book, book2);
 I don't know yet.

User code running inside a task propagated back to a calling thread is throwing unhandled
exceptions. Which approach can you use to get access to an unhandled exception before it is
thrown?
 The AggregateException.Handle method
 The AggregateException.Flatten method
 The Task.Exception method
 The Task.Wait method
 I don't know yet.

6.

How does Language Integrated Query (LINQ) method syntax


(customers.Where(...) differ from LINQ query syntax (from customer in
customers where ...)?

 Correct -

Method syntax requires you to use anonymous classes for the rest of
the query, whereas query syntax allows you to use the let keyword with
no restrictions.

 Incorrect -

Method syntax allows you to use multiple OrderBy() methods in the


same query, whereas the query syntax only allows you to use
one orderby statement in a query.

General Information
 Your choice: incorrect -

Method syntax allows you to use the let keyword with no restrictions,
whereas the query syntax requires you to use anonymous classes for
the rest of the query.

 Incorrect -

Method syntax only allows you to use one OrderBy() method in a query,
whereas query syntax allows you to use multiple orderby statements in
the same query.

 Incorrect -

I don't know yet.

8.

Which namespace and class cancels a Threading.Tasks.Task in .NET?

 Incorrect -

System.Threading.CancellationTokenTask

 Correct -

System.Threading.CancellationTokenSource

General Information
 Your choice: incorrect -

System.Threading.CancellationToken

 Incorrect -

System.Threading.Tasks.CancellationTokenSource

 Incorrect -

I don't know yet.

9.

What is the rank of the following array?


int[][] frequencies = {
new int[] { 2, 4 },
new int[] { 8, 10, 2 },
new int[] { 5, 3 },
new int[] { 0 }
};

 Correct -

 Incorrect -

General Information
 Your choice: incorrect -

 Incorrect -

 Incorrect -

I don't know yet.

14.

Given the following declaration:


string[] towns = { "London", "Southampton", "San
Francisco", "Liverpool", "Shanghai" };
What is the correct way to return a collection in which the towns are grouped
according to their first letter?

 Correct -

var townsGrouped = from town in towns


group town by town[0];

 Incorrect -

var townsGrouped = from town in towns


group town by town[0]
select town;

General Information
 Your choice: incorrect -

var townsGrouped = from town in towns


group by town[0];

 Incorrect -

var townsGrouped = from town in towns


group town by town[0]
select town.Value;

 Incorrect -

I don't know yet.

15.

The following code will not compile in C# version 8.0. Why?


using System;
interface Interface1 {
void display_1();
public void display1() {
Console.WriteLine("Hello World 1!!");
}
}

interface Interface2 : Interface1 {


public void Interface1.display1() {
Console.WriteLine("Hello World 2!!");
}
}

 Incorrect -

General Information
The display1() method in Interface2 must be declared overrides.

 Your choice: incorrect -

The display1() method in Interface1 must be declared virtual.

 Incorrect -

The display1() method in Interface1 cannot use any access modifiers.

 Correct -

The display1() method in Interface2 cannot use any access modifiers.

 Incorrect -

I don't know yet

16.

Which is the correct Event Handler to use when declaring an event called
ReturnClicked?

 Incorrect -

public event void ReturnClicked(object, EventArgs);

 Your choice: incorrect -

General Information
public event EventHandler ReturnClicked(object sender,
EventArgs e);

 Incorrect -

public EventHandler<EventArgs> ReturnClicked;

 Correct -

public event EventHandler<EventArgs> ReturnClicked;

 Incorrect -

I don't know yet.

18.

Consider the following snippet of code:


using System.Threading.Tasks;

public class Example


{
public static void Example()
{
Thread.CurrentThread.Name = "WriteMessage";
Task taskA = new Task( () =>
Console.WriteLine("Hello World."));
// BEGIN taskA

}
}
How do you begin running taskA?

General Information
 Incorrect -

if (taskA.Exists)
{
taskA.Start();
}

 Your choice: incorrect -

taskA.Run()

 Incorrect -

var result = taskA.Start();

 Correct -

taskA.Start();

 Incorrect -

I don't know yet.

1.

General Information
The variable i is declared and then initialized in the following for loop. What
value will the following code display on the console?
int i;
for (i = 0; i < 10; i++)
{
}
Console.WriteLine(i);

 Your choice: incorrect -

 Incorrect -

 Incorrect -

 Correct -

10

 Incorrect -

I don't know yet.

2.

General Information
The following using directives have been added to a class. What is the
purpose of adding directives?
using System;
using System.Data;
using System.Linq;
using System.Text;

 Incorrect -

To allow access to protected libraries within the referenced namespaces

 Correct -

To allow the use of types in a namespace without having to fully qualify


each individual use

 Your choice: incorrect -

To allow access to public members without having to qualify the access


with the type name

 Incorrect -

To prevent implementing methods that would conflict with the library


namespaces

 Incorrect -

I don't know yet.

3.

General Information
A C# application requires a connection to an associated database. When
setting up a connection with the SqlConnection class, you want the scope
of the connection variable to live only until the connection is closed. How can
you do this?

 Incorrect -

Import the namespace at the top of the file with a using statement:
using System.Data.SqlClient;

 Your choice: correct -

Use the using block:


using (var connection = new SqlConnection(<connString>)) {
//do stuff
}

 Incorrect -

Import the reference into the application as a resource.

 Incorrect -

Declare the connection in the application settings and call it in the code.
var connection = Properties.Settings.Default.connection;

 Incorrect -

I don't know yet.

4.

General Information
Which method is the safest way to convert an unknown string value to a
numeric value?

 Correct -

bool isNum = Int32.TryParse(value, out number);


if (isNum){
/*action*/
}
else{
/*action*/
}

 Incorrect -

Convert.ToInt32(someValue);

 Your choice: incorrect -

if(someValue.ToString()){
someValue = 0;
}
else if (someValue.ToInt32){
someValue = Convert.ToInt32(someValue);
}
else{
someValue = null;
}

 Incorrect -

try{
return Convert.ToInt32(someValue);
}

General Information
catch(Exception ex)
return ex.Message;}

 Incorrect -

I don't know yet.

5.

Regarding Unix time, what is the significance of (1970, 1, 1, 0, 0, 0)?

 Incorrect -

It represents the Unix epoch, which is the number of days since


midnight (UTC) on January 1st, 1970.

 Incorrect -

It represents the Unix epoch, which is the number of hours since


midnight (UTC) on January 1st, 1970.

 Incorrect -

It represents the Unix epoch, which is the number of minutes since


midnight (UTC) on January 1st, 1970.

 Your choice: correct -

It represents the Unix epoch, which is the number of seconds since


midnight (UTC) on January 1st, 1970.

General Information
 Incorrect -

I don't know yet.

6.

The following code gives an output of "1020":


string str1 = "10";
string str2 = "20";
string str3 = str1 + str2;
How can you create a new variable, str4 which has a value of "20", based
on str3?

 Your choice: incorrect -

string str4 = str3.Substring(0, 2);

 Incorrect -

string str4 = str3.Substring(1, 2);

 Correct -

string str4 = str3.Substring(2);

 Incorrect -

string str4 = str3.Substring(0);

 Incorrect -

General Information
I don't know yet.

7.

Which statement most accurately describes a C# class constructor?

 Incorrect -

The constructor must initialize static variable values.

 Your choice: correct -

The constructor must have the same name as the class.

 Incorrect -

Classes without constructors require the keyword new before they can be
instantiated as an object.

 Incorrect -

Classes are required to have at least one constructor.

 Incorrect -

I don't know yet.

8.

How would you provide a custom implementation of the


standard ToString() method in your own type?

General Information
 Your choice: incorrect -

private override string ToString() { // ...

 Incorrect -

public virtual string ToString() { // ...

 Correct -

public override string ToString() { // ...

 Incorrect -

public string ToString() { // ...

 Incorrect -

I don't know yet.

9.

Given the following class, which line of code would create an instance of this
class and set the new instance's attributes?
public class Table{
string _color;
int _width;
int _height;
public Table(string color, int width, int height){
this._color = color;
this._width = width;

General Information
this._height = height;
}
}

 Incorrect -

var table = new Table(){


color:"brown",
width:60,
height:30
}

 Incorrect -

var table = new Table();


table.color = "brown";
table.width = 60;
table.height = 30;

 Your choice: correct -

var table = new Table("brown", 60, 30);

 Incorrect -

var table = new Table(color = "brown", width = 60, height =


30);

 Incorrect -

I don't know yet.

10.

General Information
Which line of code is an example of instantiating a Dictionary<TKey,
TValue> without adding initial values?

 Correct -

Dictionary<string, string> d = new Dictionary<string,


string>();

 Incorrect -

Dictionary<string, string> d = new Dictionary<null,


null>();

 Your choice: incorrect -

Dictionary<string, string> d = new Dictionary<string,


string>(null, null);

 Incorrect -

Dictionary<string, string> d = new Dictionary<string,


string>;

 Incorrect -

I don't know yet.

11.

Consider the following array:


Book[] bookArray = {
new Book() { Id = 1, Category = "Fiction", PubYear =

General Information
1997 },
new Book() { Id = 2, Category = "Bios & Memoirs",
PubYear = 2015 },
new Book() { Id = 3, Category = "Business", PubYear =
2015 },
new Book() { Id = 4, Category = "Classics" , PubYear =
1962 },
new Book() { Id = 5, Category = "History" , PubYear =
2001 },
new Book() { Id = 6, Category = "Fiction", PubYear =
2001 },
new Book() { Id = 7, Category = "Bios & Memoirs",PubYear
= 1997 }
};
How can you create a new list that contains all unique PubYears?

 Incorrect -

var bookId = bookArray.Distinct()


.Select(x => x.PubYear);

 Incorrect -

var bookId = bookArray.Select()


.Distinct(x => x.PubYear);

 Your choice: correct -

var bookId = bookArray.Select(x => x.PubYear)


.Distinct();

 Incorrect -

General Information
var bookId = bookArray.Select(x => x.PubYear);

 Incorrect -

I don't know yet.

12.

What happens to the resource variable once the following code executes?
using (MyExternalResource resource = new
MyExternalResource()) {
resource.DoStuff();
}

 Correct -

The garbage collector disposes of it.

 Incorrect -

It will be available to keep using.

 Your choice: incorrect -

It will be stored in memory until the application closes.

 Incorrect -

The garbage collector will temporarily dispose of it, but it will still be
available for reuse.

General Information
 Incorrect -

I don't know yet.

13.

You have the following string declaration and want to throw an exception if it is
empty. Which line of code would represent the correct way to throw an
exception?
string str = "";
//series of if statements to set the value of str
if (string.IsNullOrEmpty(str)) {
//answer here
}

 Incorrect -

throw Exception e("String cannot be empty");

 Your choice: correct -

throw new Exception("String cannot be empty");

 Incorrect -

throw new Exception e("String cannot be empty");

 Incorrect -

throw Exception("String cannot be empty");

General Information
 Incorrect -

I don't know yet.

14.

Given this enum:


[Flags] public enum Status
{
OK = 0,
Thirsty = 1,
Tired = 2,
Hungry = 4,
}
How might you implement this function so that it tests whether the Hungry flag
has been set?

public bool IsHungry(Status status)


{
// What goes here?
}

 Incorrect -

return status != Status.Hungry;

 Correct -

return status == Status.Hungry;

 Your choice: incorrect -

return (status || Status.Hungry) == 4;

General Information
 Incorrect -

return (status && Status.Hungry) > 0;

 Incorrect -

I don't know yet.

15.

Review the following snippet of code:


1) int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

2) IEnumerable<int> lowerGrades = grades.Skip(3);

3) foreach (int grade in lowerGrades) {


4) Console.Write(grade + ", ");
5) }
After executing the results are:
56, 92, 98, 85
The desired results were:
59, 82, 70
What change can you make to line 2 in this code to return the correct result
set?

 Your choice: correct -

IEnumerable<int> lowerGrades = grades.Take(3);

 Incorrect -

IEnumerable<int> lowerGrades = grades.Take(1, 3);

General Information
 Incorrect -

IEnumerable<int> lowerGrades = grades.Skip(0).Take(grades.length - 3);

 Incorrect -

IEnumerable<int> lowerGrades = grades.Take(1);

 Incorrect -

I don't know yet.

16.

Which line of code represents an implementation of a generic?

 Incorrect -

public override void method1()

 Your choice: correct -

public class Class1<T> : Class2

 Incorrect -

public class Class1 : Class2

 Incorrect -

General Information
public class Class1<out>

 Incorrect -

I don't know yet.

17.

Review the following class Automobile:


public class Automobile
{
private static int CarId;
protected Drawing.Color AutoColor;

Automobile(int carId, Drawing.Color color)


{
CarId = carId;
AutoColor= color;
}
}
Which class correctly demonstrates a class inheriting the class Automobile?

 Incorrect -

public class Car : Automobile(1, Color.Red)


{

 Your choice: correct -

public class Car : Automobile


{

General Information
 Incorrect -

public class Car : Automobile()


{
private Automobile auto = new Automobile(1, Color.Red);
}

 Incorrect -

public class Car


{
private Automobile auto = new Automobile(1, Color.Red);
}

 Incorrect -

I don't know yet.

18.

The following if/else statement determines if a randomly generated


number between 1 and 10 is a low, medium, or high number. It uses the
following criteria:

- Less than 3: Low number;


- Between 3 and 6: Middle number;
- Between 7 and 9: High number;
- 10: 10

How would you convert this if statement to a switch statement?


int num = new Random().Next(1, 11);
if (num < 3)
Console.WriteLine("Low number");
else if (num >= 3 && num <= 6)
Console.WriteLine("Middle number");
else if (num > 6 && num < 10)
Console.WriteLine("High number");

General Information
else
Console.WriteLine("10");

 Your choice: correct -

switch (num) {
case 1: case 2:
Console.WriteLine("Low number");
break;
case 3: case 4: case 5: case 6:
Console.WriteLine("Middle number");
break;
case 7: case 8: case 9:
Console.WriteLine("High number");
break;
default:
Console.WriteLine("10");
break;
}

 Incorrect -

switch (num) {
case 1 || case 2:
Console.WriteLine("Low number");
break;
case 3 || case 4 || case 5 || case 6:
Console.WriteLine("Middle number");
break;
case 7 || case 8 || case 9:
Console.WriteLine("High number");
break;
default:
Console.WriteLine("10");
break;
}

 Incorrect -

General Information
switch (num) {
case 1: case 2:
Console.WriteLine("Low number");
break;
case 3: case 4: case 5: case 6:
Console.WriteLine("Middle number");
break;
case 7: case 8: case 9:
Console.WriteLine("High number");
break;
else:
Console.WriteLine("10");
break;
}

 Incorrect -

switch (num) {
case 1: case 2:
Console.WriteLine("Low number");
case 3: case 4: case 5: case 6:
Console.WriteLine("Middle number");
case 7: case 8: case 9:
Console.WriteLine("High number");
default:
Console.WriteLine("10");
}

 Incorrect -

I don't know yet.

19.

Which statement is true regarding these two classes?


public class WorkItem
{
private static int currentID;
protected int ID { get; set; }
public WorkItem()

General Information
{
ID = 0; //default id
}
protected int GetNextID()
{
return ++currentId;
}
}

public class ChangeRequest : WorkItem


{
protected int originalItemID { get; set; }
public ChangeRequest (int originalID)
{
this.ID = GetNextID();
this.originalItemID = originalID;
}
}

 Incorrect -

ChangeRequest is a reusable component that can be extended from other


classes.

 Incorrect -

WorkItem is a static, reusable component that is being extended from the


class ChangeRequest.

 Incorrect -

WorkItem is an abstract, reusable component that is being extended from


the class ChangeRequest.

General Information
 Your choice: correct -

WorkItem is an example of a reusable component that is being extended


by the class ChangeRequest.

 Incorrect -

I don't know yet.

20.

Consider the following class:


public class Animal
{
private string _species;

public Animal(string species)


{
_species = species;
}
}
You need a way to create an instance of the Animal class without providing
species. How can you do so without removing the current constructor?

 Correct -

Add a parameterless constructor.

 Your choice: incorrect -

Make the variable _species nullable.

General Information
 Incorrect -

Add a { get; set; } method for _species.

 Incorrect -

Make the parameter species nullable.

 Incorrect -

I don't know yet.

General Information

You might also like