I have inserted the following text for better accessibility during the study.
Task 1
Question:
I have inserted the following text for better accessibility during the study.
If int? i = 2;
, which of the following assigns the value 2
to j
?
Select all correct answers:
- [✔]
int j = (i is null)? 0 : i;
- None of those given
- [✔]
int j = i ?? 0;
int j = i ? i : 0;
int j = i;
Task 2
Question:
You have a class named Customer
and a class named Order
. The Customer
class has a property named Orders
that contains a list of Order
objects. The Order
class has a property named OrderDate
that contains the date of the Order
. You need to create a LINQ query that returns all of the customers who had at least one order during the year 2005.
How should you complete the code?
List<Customer> customersWithOrdersIn2005 =
customers.________(c => c.Orders.________(o => o.OrderDate.Year ________ 2005)).ToList();
To answer, drag the appropriate code elements to the correct targets in the answer area. Each code element may be used once, more than once, or not at all.
Select
=>
✔Where
✔==
✔Join
Any
✔
List< Customer > customersWithOrdersIn2005 =
customers.Where
(c => c.Orders.Any
(o =>
o.OrderDate.Year ==
2005)).ToList();
Task 3
Question:
Which of the following are the correct ways to declare a delegate for calling the function func()
defined in the sample class given below?
using System;
//...
class Sample
{
public static int func(int i, float f)
{
//...
}
}
Select all correct answers:
- delegate void d(int, float);
- [✔] delegate int d(int i, Single j);
- static func<int, float>
- delegate int Sample.func(int i, float j);
- None of those given
- func<int32, Single, Int32>
- delegate int (int i, Single j);
- delegate d(int i, Single j);
- delegate static int d(int i, float j);
Task 4
Question:
You are developing an application that uses multiple asynchronous tasks to optimize performance. The application will be deployed in a distributed environment.
You need to retrieve the result of an asynchronous task that retrieves data from a web service.
The data will later be parsed by a separate task.
How should you complete the code?
protected async void StartTask()
{
string result = ____________;
}
public ____________
{
//...
}
To answer, drag the appropriate code elements to the correct targets in the answer area. Each code element may be used once, more than once, or not at all.
await GetData()
Task<string> GetData()
await Task<string> GetData()
async GetData()
GetData()
async Task<string> GetData()
protected async void StartTask()
{
string result = await GetData();
}
public Task<string> GetData()
{
//...
}
Task 5
Question:
You have the following class RaceSpeedRecord
:
public class RaceSpeedRecord
{
public RaceSpeedRecord Faster;
public RaceSpeedRecord Slower;
public string Race;
public double Time;
}
The code that manages the list is as follows:
public class Results
{
public Results()
{
CurrentOlympicRecord = new RaceSpeedRecord();
}
public RaceSpeedRecord CurrentOlympicRecord;
public void AddRace(string raceName, double time)
{
}
}
You need to implement the AddRace
method.
Match the code segment to its location.
public void AddRace(string raceName, double time)
{
var current = CurrentOlympicRecord;
while (________ > time)
{
current = ________;
}
var race = new RaceSpeedRecord
{
Race = raceName,
Time = time,
Faster = ________,
Slower = ________
};
current.Faster.Slower = race;
current.Slower.Faster = race;
}
Options to insert:
current.Race
current.Slower
current.Time
current.Faster
??
public void AddRace(string raceName, double time)
{
var current = CurrentOlympicRecord;
while (current.Time > time)
{
current = current.Slower;
}
var race = new RaceSpeedRecord
{
Race = raceName,
Time = time,
Faster = current.Faster,
Slower = current
};
if (current.Faster != null)
{
current.Faster.Slower = race;
}
current.Faster = race;
}
??
Task 6
Question:
Write an extension method for the IEnumerable
sequence of integers that calculates the median (middle value in a sorted sequence). If the sequence is empty or null
, return null
. Infer the method signature and its wrapping from the provided examples.
Your code will be embedded in the following template, compiled, and run for several test cases:
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyProg
{
{{ STUDENT_ANSWER }}
public class Program
{
public static void Main(string[] args)
{
{{ TEST.testcode }}
}
}
}
For example:
Test | Result |
---|---|
int[] tab = {2, 3, 1}; Console.WriteLine(tab.Mediana()); |
2 |
int[] tab = {2, 3, 1, 4}; Console.WriteLine(tab.Mediana()); |
2.5 |
List<int> tab = new List<int>(); if(tab.Mediana() != null) Console.WriteLine(tab.Mediana()); else Console.WriteLine("data set is empty"); |
data set is empty |
Answer:
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyProg
{
public static class Extensions
{
public static double? Mediana(this IEnumerable<int> source)
{
if (source == null || !source.Any())
{
return null;
}
var sortedList = source.OrderBy(n => n).ToList();
int count = sortedList.Count;
if (count % 2 == 0)
{
// If the number of elements is even, return the average of the two middle elements
return (sortedList[count / 2 - 1] + sortedList[count / 2]) / 2.0;
}
else
{
// If the number of elements is odd, return the middle element
return sortedList[count / 2];
}
}
}
public class Program
{
public static void Main(string[] args)
{
int[] tab1 = { 2, 3, 1 };
Console.WriteLine(tab1.Mediana()); // Expected result: 2
int[] tab2 = { 2, 3, 1, 4 };
Console.WriteLine(tab2.Mediana()); // Expected result: 2.5
List<int> tab3 = new List<int>();
if (tab3.Mediana() != null)
{
Console.WriteLine(tab3.Mediana());
}
else
{
Console.WriteLine("data set is empty"); // Expected result: data set is empty
}
}
}
}
Task 7
Question:
Create a generator (function generating a sequence) with the signature public static IEnumerable<int> CiagZeroJeden(int n)
returning for the given parameter n
being a positive integer, the first n
elements of the sequence 0 1 0 1 0 1 0 1 ...
.
Your code will be pasted as a method into the Program
class and then verified by tests run in the Main()
method. Using LINQ operators is prohibited.
For example:
Test | Result |
---|---|
foreach(var x in CiagZeroJeden(10)) { Console.Write($"{x} "); } |
0 1 0 1 0 1 0 1 0 1 |
Answer:
public static IEnumerable<int> CiagZeroJeden(int n)
{
for (int i = 0; i < n; i++)
{
yield return i % 2;
}
}
Task 8
Question:
You are building an application in Microsoft Visual Studio 2019. You have the following code:
#define DEBUG
using System;
using System.Diagnostics;
public class TestClass
{
[Conditional("DEBUG")]
public void LogData()
{
Trace.Write("LogData1");
}
public void RunTestClass()
{
this.LogData();
#if DEBUG
Trace.Write("LogData2");
#endif
}
}
Mark all statements that are true.
Select one answer:
- When
RunTestClass
executes, onlyLogData2
will be written if the application starts in RELEASE mode. - [✔] When
RunTestClass
executes, nothing will be written if the application starts in RELEASE mode. - When
RunTestClass
executes,LogData1
andLogData2
will be written if the application starts in RELEASE mode. - When
RunTestClass
executes, onlyLogData1
will be written if the application starts in RELEASE mode.
Task 9
Question:
You are developing an application, that reads the XML streams by using DataContractSerializer
object that is declared by the following code segment:
var ser = new DataContractSerializer(typeof(Name));
The XML streams are in the following format:
<Name xmlns="http://www.northwind.com/2017/01">
<LastName>Jones</LastName>
<FirstName>David</FirstName>
</Name>
You need to ensure that the application preserves the element ordering as provided in the XML stream.
How should you complete the relevant code?
[__________]
class Name
{
[__________]
public string FirstName { get; set; }
[__________]
public string LastName { get; set; }
}
To answer, drag the appropriate code elements to the correct targets in the answer area. Each code element may be used once, more than once, or not at all.
[Deserialize(Order=1)]
✔[Deserialize(Order=0)]
✔[DataMember]
[DataContractDeserializer(Name="http://www.northwind.com/2017/01")]
[Datamember(Name="http://www.northwind.com/2017/01")]
[DataContract(Name="http://www.northwind.com/2017/01")]
✔[DataContract]
[Datamember(Order=7)]
[DataContract(Name="http://www.northwind.com/2017/01")]
class Name
{
[DataMember(Order=1)]
public string FirstName { get; set; }
[DataMember(Order=0)]
public string LastName { get; set; }
}
Task 10
Question:
Which of the following statements are correct about structs for C# 8?
Select all correct answers:
- [✔] Within a
struct
declaration, fields cannot be initialized unless they are declared asconst
orstatic
. - [✔] Structs cannot inherit from another struct, but can implement interfaces.
- Struct members can be declared as
protected
. - None of those given.
- [✔] A
struct
may not declare a default constructor (a constructor without parameters) or a destructor.
Task 11
Question:
Boxing refers to:
Select all correct answers:
- creating a class to wrap functionality in a single entity
- [✔] converting a value type to a reference type
- encapsulation
- none of those given
- converting a reference type to a value type
Task 12
Question:
You have the following code:
namespace MyLib
{
public class __________
{
B<__________> a = new B<__________>();
}
class __________
{
__________ A f() => this;
}
__________ class B< T > where T : A
{
protected __________ g(T a) => a.f();
}
}
You need to ensure that code compiles without warnings and errors. Deduce the types and access modifiers.
Drag the appropriate code elements to the correct targets in the answer area. Each code element may be used once, more than once, or not at all. All answer areas must be completed.
Answer:
??
namespace MyLib
{
public class Class1
{
B<Class2> a = new B<Class2>();
}
class Class2 : A
{
Class2 A f() => this;
}
public class B<T> where T : A
{
protected T g(T a) => a.f();
}
}
??
Task 13
Question:
You are developing a custom collection named LoanCollection
for a class named Loan
.
You need to ensure that you can process each Loan
object in the LoanCollection
collection by using a foreach
loop.
How should you complete the code?
public class LoanCollection : __________
{
private readonly Loan[] _loanCollection;
public LoanCollection(Loan[] loanArray)
{
_loanCollection = new Loan[loanArray.Length];
for (int i = 0; i < loanArray.Length; i++)
{
_loanCollection[i] = loanArray[i];
}
}
__________
__________
}
To answer, drag the appropriate code elements to the correct targets in the answer area. Each code element may be used once, more than once, or not at all.
return _loanCollection.GetEnumerator();
✔: IEnumerable
✔public IEnumerator GetEnumerator()
✔: IComparable
: IDisposable
return obj == null ? 1 : _loanCollection.Length
public int CompareTo(object obj)
_loanCollection[i].Amount++;
public void Dispose()
Answer:
public class LoanCollection : IEnumerable
{
private readonly Loan[] _loanCollection;
public LoanCollection(Loan[] loanArray)
{
_loanCollection = new Loan[loanArray.Length];
for (int i = 0; i < loanArray.Length; i++)
{
_loanCollection[i] = loanArray[i];
}
}
public IEnumerator GetEnumerator()
{
return _loanCollection.GetEnumerator();
}
}
Task 14
Question:
Which of the following can be declared as virtual
in a class?
Select all correct answers:
- [✔] Properties
- Fields
- Static fields
- None of those given
- Static methods
- [✔] Events
- Inner classes
- [✔] Methods
Task 15
Question:
You have the following code (line numbers are included for reference only):
01 __________ class Connection
02 {
03 public static Connection Create()
04 {
05 return new Connection();
06 }
07 __________ Connection() {}
08 }
You need to ensure that new instances of Connection
can be created only by other classes by calling the Create
method. The solution must allow classes to inherit from Connection
.
What should you do?
To answer, drag the appropriate code elements to the correct targets in the answer area. Each code element may be used once, more than once, or not at all.
public static
public abstract
public
✔protected Connection() {}
✔private Connection() {}
public Connection() {}
Answer:
public class Connection
{
public static Connection Create()
{
return new Connection();
}
protected Connection() {}
}
Task 16
Question:
You are developing a class named EmployeeList
. The following code implements the EmployeeList
class:
public class EmployeeList
{
private Dictionary<string, decimal> employees = new Dictionary<string, decimal>(); // X
public void Add(string name, decimal salary)
{
employees.Add(name, salary);
}
// Y
}
You create the following unit test method to test the EmployeeList
class implementation:
public void UnitTest1()
{
var employees = new EmployeeList();
employees.Add("John", 1000m);
employees.Add("David", 5000m);
decimal expectedSalary = 5000m;
decimal actualSalary = employees["David"];
Assert.AreEqual(expectedSalary, actualSalary);
}
You need to ensure that the unit test will pass. What should you do?
Select the correct answer:
-
[✔] Insert the following code segment at line // Y:
public decimal this[string name] => employees[name];
-
Insert the following code segment at line // Y:
public decimal salary(string name) => employees[name];
-
Replace line // X with the following code segment:
public Dictionary<string, decimal> employees = new Dictionary<string, decimal>();
-
The code is correct, no changes needed
-
Insert the following code segment at line // Y:
public Dictionary<string, decimal> GetEmployees() => employees;
Task 17
Question:
You are developing a class named Temperature
.
You need to ensure that collections of Temperature
objects are sortable. You have the following code:
public class Temperature : __________
{
public double Fahrenheit { get; set; }
public int __________(object obj)
{
if (obj == null) return -1;
var otherTemperature = obj as Temperature;
if (otherTemperature == null)
throw new ArgumentException("Object is
not a Temperature");
return __________;
}
}
Options to insert:
otherTemperature.Fahrenheit.CompareTo(this.Fahrenheit)
this.Fahrenheit.CompareTo(otherTemperature.Fahrenheit)
✔public class Temperature : IComparable
✔CompareTo
✔Equals
public class Temperature : IComparer
Answer:
public class Temperature : IComparable
{
public double Fahrenheit { get; set; }
public int CompareTo(object obj)
{
if (obj == null) return -1;
var otherTemperature = obj as Temperature;
if (otherTemperature == null)
throw new ArgumentException("Object is not a Temperature");
return this.Fahrenheit.CompareTo(otherTemperature.Fahrenheit);
}
}
Arkadiusz Nowak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2