---
# System prepended metadata

title: C# Exam Questions 70-483 Reading - Advanced
tags: [Syntax, C#, Exam Questions, 70-483]

---

# C# Exam Questions 70-483 Reading - Advanced

###### tags: `C#` `70-483` `Exam Questions` `Syntax`

https://www.briefmenow.org/microsoft/category/exam-70-483-programming-in-c-update-july-21th-2017/page/23/

https://www.examtopics.com/exams/microsoft/70-483/

---
# Asynchronous programming

## async/ await + StreamReader 方法

You are developing an application that will include a method named ``GetData``.
The ``GetData()`` method will retrieve several lines of data
from a web service by using a ``System.IO.StreamReader`` object.
You have the following requirements:
The ``GetData()`` method must return a ``string`` value that
contains __the first line of the response__ from the web service.
The application must remain responsive while the ``GetData()`` method runs.
You need to implement the ``GetData()`` method.

```
private async void GetData(WebResponse response) {
    var streamReader = new StreamReader(response.GetResponseStream());
    urlText.Text = await streamReader.ReadToEndAsync();
}
```

---

```
public override System.Threading.Tasks.Task<string> ReadToEndAsync ();
public override System.Threading.Tasks.Task<string>? ReadLineAsync ();
```

``ReadToEndAsync()`` 取回 Non-null 的結果

---

## 2. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1250/

You are developing an application that uses multiple asynchronous tasks to optimize performance.
You need to retrieve the result of an asynchronous task.
Which code segment should you use?

A. 
```
protected async void StartTask() {
	string result = await GetData();
	...
}
public Task<string> GetData() {
	...
}
```

B. 
```
protected async void StartTask() {
	string result = GetData();
	...
}
public Task<string> GetData() {
	...
}
```

C.
```
protected async void StartTask() {
	string result = await GetData();
	...
}
public async Task<string> GetData() {
	...
}
```

D.
```
protected async void StartTask() {
	string result = await GetData();
	...
}
public await Task<string> GetData() {
	...
}
```

Answer: A, C 都可以

若 ``GetData()`` 要呼叫其它的 async task, 就要加 ``async`` keyword


---

## 3. https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-310/

You are developing an application that will include a method named ``GetData``. 
The ``GetData()`` method will retrieve several lines of data 
from a web service by using a ``System.IO.StreamReader`` object.
You have the following requirements:
The ``GetData()`` method must return a ``string`` value that 
contains __the entire response__ from the web service.
The application must remain responsive while the ``GetData()`` method runs.
You need to implement the ``GetData()`` method.
How should you complete the relevant code? 


```
public [] void GetData(WebResponse response) {
	string urlText;
    var sr = new StreamReader(response.GetResponseStream());
    urlText = [] await sr.[]
}
```

* ``ReadLineAsync();``
* ``ReadToEndAsync();``
* ``await``
* ``async``
* ``ReadLine();``
* ``ReadToEnd();``
* ``ToString();``

Answer:

```
public async void GetData(WebResponse response) {
	string urlText;
    var sr = new StreamReader(response.GetResponseStream());
    urlText = await await sr.ReadToEndAsync();
}
```

### [await await vs Unwrap()](https://stackoverflow.com/questions/34816628/await-await-vs-unwrap)

```
public async void GetData(WebResponse response) {
    var streamReader = new StreamReader(response.GetResponseStream());
    urlText.Text = await streamReader.ReadToEndAsync();
}
```


[``await await`` vs ``Unwrap()``](https://stackoverflow.com/questions/34816628/await-await-vs-unwrap)


[TaskExtensions.Unwrap Method](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskextensions.unwrap?redirectedfrom=MSDN&view=netcore-3.1)

Unwrap(Task<Task>)
Creates a proxy Task that represents the asynchronous operation of a TryExecuteTaskInline(Task, Boolean).

[Double await in one call](https://stackoverflow.com/questions/35668622/double-await-in-one-call)

```
await await Task.WhenAny(killJoy.Task, Task.WhenAll(tasks));
```

``Task.WhenAny`` is going to return a ``Task<Task<TResult>>``:

* Awaiting the result of ``Task.WhenAny()`` will return the first task that completed
* Awaiting that task will return the results of the task, i.e. a ``TResult[]``.
You might find it easy to understand with explanatory variables:

```
var firstCompletedTask = await Task.WhenAny(killJoy.Task, Task.WhenAll(tasks));
var firstResult = await firstCompletedTask;
return firstResult;
```

It's not clear why you're concerned around the performance of this - 
it's just two await expressions, 
not particularly different to any other method with two await expressions.

It's pretty natural to do this when using ``Task.WhenAny<TResult>(Task<TResult>[])``, 
given that the return type is a ``Task<Task<TResult>>``.


---

# Task

## 1. ``TaskCompletionSource<TResult>`` + ``Task.Factory.StartNew``

### 1.1. https://www.briefmenow.org/microsoft/which-two-actions-should-you-perform-1396/

You are implementing a new method named ``ProcessData``. 
The ``ProcessData()`` method calls a third-party component that performs a long-running operation.
The third-party component uses the ``IAsyncResult`` pattern 
to signal completion of the long-running operation.
You need to ensure that the calling code handles the long-running operation 
as a ``System.Threading.Tasks.Task`` object.
Which two actions should you perform?

A. Call the component by using the ``TaskFactory.FromAsync()`` method.

B. Create a ``TaskCompletionSource<T>`` object.

C. Apply the async modifier to the method signature.

D. Apply the following attribute to the method signature:
``[MethodImpl(MethodImplOptions.Synchronized)]``


Answer: A, B

---

### [Task.Factory.StartNew vs Task.Factory.FromAsync](https://stackoverflow.com/questions/17432306/task-factory-startnew-vs-task-factory-fromasync)

### [TaskFactory.FromAsync Method]()
* Namespace: ``System.Threading.Tasks``
* Creates a Task that represents a pair of begin and end methods that 
conform to the Asynchronous Programming Model pattern.

#### 
Creates a Task that executes an end method action when a specified IAsyncResult completes.

```
public System.Threading.Tasks.Task FromAsync (IAsyncResult asyncResult, Action<IAsyncResult> endMethod);
```

---

### [TaskCompletionSource<TResult> Class](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcompletionsource-1?view=netcore-3.1)
#### Remark
In many scenarios, it is useful to enable a ``Task<TResult>`` 
to represent an external asynchronous operation. 
``TaskCompletionSource<TResult>`` is provided for this purpose. 
__It enables the creation of a task that can be handed out to consumers__. 
The consumers can use the members of the task the same way 
as they would in any other scenario handling task member variables. 
However, unlike most tasks, the state of a task created by a ``TaskCompletionSource`` 
is controlled explicitly by the methods on ``TaskCompletionSource``. 
This enables the completion of the external asynchronous operation 
to be propagated to the underlying Task. 
The separation also ensures that consumers are not able to 
transition the state without access to the corresponding ``TaskCompletionSource``. 
For more information, see the entry [The Nature of TaskCompletionSource<TResult>](https://devblogs.microsoft.com/pfxteam/the-nature-of-taskcompletionsourcetresult/) 
in the Parallel Programming with .NET blog.


```
var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ... );
task.Wait();
// or
await task;
//or
task.ContinueWith(() => /* rest of the method here */);
```


---

## 2. ``Task.ContinueWith()``

You use the ``Task.Run()`` method to launch a long-running data processing operation. 
The data processing operation often fails in times of heavy network congestion.
If the data processing operation fails, 
__a second operation must clean up any results of the first operation__.
You need to ensure that __the second operation is invoked 
only if the data processing operation throws an unhandled exception__.
What should you do?

Create a task by calling the ``Task.ContinueWith()`` method.


``ContinueWith`` defines an additional task
that corresponds to what should happen when the previous task completes.

adding a ``ContinueWith`` with ``TaskContinuationOptions.OnlyOnFaulted``
where you can log any exceptions that may arise.


### [Task.ContinueWith](https://docs.microsoft.com/zh-tw/dotnet/api/system.threading.tasks.task.continuewith?view=netcore-3.1)

example:
```
static Task SaveImage(byte[] bytes, string imagePath) { ... }

SaveImage(originalImageBytes, originalImagePath)
.ContinueWith(task2 => {
    ...
});
```

---

## 3. Task cancellation

### 1. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-in-the-method-body-8/

You are implementing a method named ``ProcessReports`` that performs a long-running task. 
The ``ProcessReports()`` method has the following method signature:
```
public void ProcessReports(List<decimal> values, CancellationTokenSource cts, CancellationToken ct)
```

If the calling code requests cancellation, 
the method must perform the following actions:
Cancel the long-running task.
Set the task status to ``TaskStatus.Canceled``.
You need to ensure that the ``ProcessReports()`` method performs the required actions.
Which code segment should you use in the method body?


A.
```
if (ct.IsCancellationRequested)
return;
```

B. ``ct.ThrowIfCancellationRequested();``

C. ``cts.Cancel();``

D. ``throw new AggregateException();``

Answer: B

---

### [Task cancellation](https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation)

In the Task classes, cancellation involves 
cooperation between the user delegate, 
which represents a cancelable operation, 
and the code that requested the cancellation. 
A successful cancellation involves the requesting code 
calling the ``CancellationTokenSource.Cancel()`` method 
and the user delegate terminating the operation in a timely manner. 
You can terminate the operation by using one of these options:

* By simply returning from the delegate. 
In many scenarios this is sufficient; however, 
a task instance that is canceled in this way transitions 
to the ``TaskStatus.RanToCompletion`` state, 
not to the TaskStatus.Canceled state.

* By throwing a ``OperationCanceledException`` and 
passing it the token on which cancellation was requested. 
The preferred way to do this is to use the ``ThrowIfCancellationRequested`` method. 
A task that is canceled in this way transitions to the ``Canceled`` state, 
which the calling code can use to verify that 
the task responded to its cancellation request.

---

When a task instance observes an ``OperationCanceledException`` thrown by user code, 
it compares the exception's token to its associated token 
(the one that was passed to the API that created the Task). 
If they are the same and 
the token's ``IsCancellationRequested`` property returns ``true``, 
the task interprets this as acknowledging cancellation and 
__transitions to the ``Canceled`` state__. 
If you do not use a ``Wait`` or ``WaitAll`` method to wait for the task, 
then the task just sets its status to ``Canceled``.



---

# LinQ

## 1. 

### 1.1.

You are developing an application by using C#. 
The application includes __an array of decimal values__ named ``loanAmounts``. 
You are developing a __LINQ query__ to return the values from the array.

The query must return decimal values that are evenly divisible by two. 
The values must be sorted from the lowest value to the highest value.
You need to ensure that the query correctly returns the decimal values.

```
IEnumerable<decimal> loanAmounts =
from amount in loanAmounts
where amount % 2 == 0
orderby amount ascending
select amount;
```

select 放最後

---

### 1.2. https://www.briefmenow.org/microsoft/you-need-to-create-a-method-that-returns-a-list-of-vali/

You need to create a method that returns a list of vali…

You have a method named ``GetCustomerIDs`` that returns a list of integers. 
Each entry in the list represents a customer ID that 
is retrieved from a list named ``Customers``. 
The ``Customers`` list contains 1,000 rows.
Another developer creates a method named ``ValidateCustomer`` 
that __accepts an ``integer`` parameter and returns a ``Boolean`` value__. 
``ValidateCustomer`` returns ``true`` 
if __the integer provided references a valid customer__.
``ValidateCustomer`` can take up to one second to run.
You need to create a method that returns a list of valid customer IDs. 
The code must execute in the shortest amount of time.
What should you do? 

* ``public List<Int32> GetValidCustomers() {``

* ``Task<List<Int32>> validCustomers = ``

* 
```
from c in customers
where ValidateCustomer(c)
select c)
.ToList();
```

* ``return validCustomers; }``

* 
```
from c in customers
where ValidateCustomer(c)
select c)
.AsParallel().ToList();
```

* ``public async Task<List<Int32>> GetValidCustomers()``

* 
```
from c in customers.AsParallel()
where ValidateCustomer(c)
select c)
.ToList();
```

* ``List<Int32> validCustomers = ``

---

Answer:

```
List<Int32> validCustomers = 
    (from c in customers
    where ValidateCustomer(c)
    select c)
    .AsParallel()
    .ToList();
```


---

### 1.3. 

You are developing an application.
The application calls a method that
__returns an array of integers named ``employeeIds``__.
You define an integer variable named ``employeeIdToRemove`` and assign a value to it.
You declare an array named ``filteredEmployeeIds``.
You have the following requirements:
Remove duplicate integers from the ``employeeIds`` array.
Sort the array in order from the highest value to the lowest value.
Remove the integer value stored in the ``employeeIdToRemove`` variable 
from the ``employeeIds`` array.

You need to __create a LINQ query__ to meet the requirements.
Which code segment should you use?

```
int[] filteredEmployeeIds = employeeIds
.Distinct() // Remove duplicate integers from the employeeIds array.
.Where(value => value != employeeIdToRemove) // Remove the integer value stored in the employeeIdToRemove variable 
.OrderByDescending(x => x) // Sort the array in order from the highest value to the lowest value.
.ToArray(); // returns an array of integers
```

---

### 1.4. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1243/

You are developing an application. 
The application calls a method that 
returns an array of integers named ``customerIds``. 
You define an integer variable named ``customerIdToRemove`` and assign a value to it. 
You declare an array named ``filteredCustomerIds``.
You have the following requirements.
Remove duplicate integers from the ``customerIds`` array.
Sort the array in order from the highest value to the lowest value.
Remove the integer value stored in the ``customerIdToRemove`` variable from the ``customerIds`` array.
You need to create a LINQ query to meet the requirements.
Which code segment should you use?

A.
```
int[] filteredCustomerIds = customerIds
.Distinct()
.OrderByDescending(x => x)
.ToArray();
```

B.
```
int[] filteredCustomerIds = customerIds
.Where(value => value != customerIdToRemove)
.OrderByDescending(x => x)
.ToArray();
```

C.
```
int[] filteredCustomerIds = customerIds
.Distinct()
.Where(value => value != customerIdToRemove)
.OrderByDescending(x => x)
.ToArray()
```

D.
```
int[] filteredCustomerIds = customerIds
.Where(value => value != customerIdToRemove)
.OrderBy(x => x)
.ToArray();
```

Answer: C

```
int[] filteredCustomerIds = customerIds
.Distinct()
.Where(value => value != customerIdToRemove) // Remove the integer value stored in the employeeIdToRemove variable 
.OrderByDescending(x => x) // Sort the array in order from the highest value to the lowest value.
.ToArray(); // returns an array of integers
```

---

### 1.5. https://www.briefmenow.org/microsoft/hot-area-90/

You define a class by using the following code:

```
public class Department {
	public int Id { get; set; }
	public string Name { get; set; }
	public string Manager { get; set; }
	public int BuildingId { get; set; }
}
```

You create a collection by using the following code:

```
Department[] departments = {
	new Department { Id = 1, Name = "Accounting", Manager = "User1", BuildingId = 15 },
	new Department { Id = 2, Name = "Sales", Manager = "User2", BuildingId = 3 },
	new Department { Id = 3, Name = "IT", Manager = "User3", BuildingId = 15 },
	new Department { Id = 4, Name = "Marketing", Manager = "User4", BuildingId = 3 },
};
var output = from d in departments
group d by d.BuildingId into dp
select new { sorted = dp.Key, Department = dp };
```

To answer, complete each statement according to the information presented in the code.

The output collection will contain [] object(s).
--> ``2``
The sorted property of the output collection will be the [] type.
--> ``int`` (the BuildingId)

---

## 2. LinQ, Regular Expression, MatchCollection Class 

### 2.1. https://www.briefmenow.org/microsoft/which-two-code-segments-can-you-use-to-achieve-this-goal-26/

You are implementing a method named ``GetValidEmailAddresses``. 
The ``GetValidEmailAddresses()`` method processes a list of ``string`` values 
that represent email addresses. The ``GetValidEmailAddresses()`` method 
must return only email addresses that are in a valid format.
You need to implement the ``GetValidEmailAddresses()`` method.
Which two code segments can you use to achieve this goal? 


A. 
```
private static List<String> GetValidEmailAddresses(string input, string pattern) {
	var regex = new Regex(pattern);
	var matches = regex.Matches(input);
	foreach(Match match in matches) {
		if(!match.Success) {
			validEmailAddresses.Add(match.Value);
		}
	}
	return validEmailAddresses;	
}
```

B.
```
private static List<String> GetValidEmailAddresses(string input, string pattern) {
	var regex = new Regex(pattern);
	var matches = regex.Matches(input);
	return (
		from Match match in matches
		where match.Success
		select match.Value
		).ToList();
}
```

C.
```
private static List<String> GetValidEmailAddresses(string input, string pattern) {
	var regex = new Regex(pattern);
	var matches = regex.Matches(input);
	return (
		from Match match in matches
		where match.Success
		select match.Success.ToString()
		).ToList();
}
```

D. 
```
private static List<String> GetValidEmailAddresses(string input, string pattern) {
	var regex = new Regex(pattern);
	var matches = regex.Matches(input);
	var validEmailAddresses = new List<String>();
	foreach(Match match in matches) {
		if(match.Success) {
			validEmailAddresses.Add(match.Value);
		}
	}
	return validEmailAddresses;	
}
```

Answer: B, D

---

## 3. ``Take``, ``Skip``, ``First``

### 3.1.

You have an application that uses paging.
Each page displays five items from a list.
You need to display the second.
Which three code blocks should you use to develop the solution.

* ``.Take(1)``
* ``.Skip(2)``
* ``.First(5)``
* ``.Skip(5)``
* ``.Skip(1)``
* ``.Take(5)``
* ``.Skip(1)``
* ``var page = items``
* ``int page = items``

Answer:

```
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,
                    83, 23, 87, 435, 67, 12, 19 };
var page = numbers.Skip(5).Take(5);
foreach(var item in page) {
    Console.WriteLine(item);
}
/*
 This code produces the following output:
 435
 3
 54
 83
 23
*/
```

---

### 1. ``First``

[Enumerable.First Method](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.first?view=netcore-3.1)
* Namespace: ``System.Linq``


#### 1.1. Returns the first element of a sequence.
```
public static TSource First<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);
```

```
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,
                    83, 23, 87, 435, 67, 12, 19 };

int first = numbers.First();
Console.WriteLine(first);

/*
 This code produces the following output: 9
*/
```

#### 1.2. Returns the first element in a sequence that satisfies a specified condition.

```
public static TSource First<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);
```

```
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,
                    83, 23, 87, 435, 67, 12, 19 };

int first = numbers.First(number => number > 80);
Console.WriteLine(first);
/*
 This code produces the following output: 92
*/
```

### 3. ``Take``

[Enumerable.Take<TSource>(IEnumerable<TSource>, Int32) Method](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take?view=netcore-3.1)
* Namespace: ``System.Linq``
* Returns a specified number of contiguous elements from the start of a sequence.


```
public static System.Collections.Generic.IEnumerable<TSource> Take<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int count);
```

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

IEnumerable<int> topThreeGrades =
    grades.OrderByDescending(grade => grade).Take(3);

Console.WriteLine("The top three grades are:");
foreach (int grade in topThreeGrades)
{
    Console.WriteLine(grade);
}
/*
 This code produces the following output:
 The top three grades are:
 98
 92
 85
*/
```

### 4. ``Skip``
[Enumerable.Skip<TSource>(IEnumerable<TSource>, Int32) Method](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.skip?view=netcore-3.1)
* Namespace: ``System.Linq``
* Bypasses a specified number of elements in a sequence and then returns the remaining elements.

```
public static System.Collections.Generic.IEnumerable<TSource> Skip<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int count);
```

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

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

Console.WriteLine("All grades except the top three are:");
foreach (int grade in lowerGrades) {
    Console.WriteLine(grade);
}

/*
 This code produces the following output:

 All grades except the top three are:
 82
 70
 59
 56
*/
```

### 5. ``Any``

### [Enumerable.Any Method](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netcore-3.1)
* Namespace: ``System.Linq``
* Determines whether any element of a sequence exists or satisfies a condition.

---

### 3.2. https://www.briefmenow.org/microsoft/you-need-to-display-the-third-page-4/

You have an application that uses paging. 
Each page displays 10 items from a list.
You need to display the third page. 
Select and Place:

* ``.Skip(2)``
* ``.First(10)``
* ``.Take(10)``
* ``var page = items``
* ``.Take(1)``
* ``.Skip(30)``
* ``int page = items``
* ``.Skip(20)``

Answer: 

``var page = items.Skip(20).Take(10);``


---

### 3.3. https://www.briefmenow.org/microsoft/which-code-should-you-use-51/

You have the following code:

```
List<Int32> items = new List<int> { 100, 95, 80, 75, 95 };
```

You need to retrieve all of the numbers from the items variable 
that are greater than 80. Which code should you use?

A.
```
var result = from i in items
where i > 80
select i;
```
B. ``var result = item.Take(80);``
C. ``var result = item.First(i => i > 80);``
D. ``var result = item.Any(i => i > 80);``

Answer: A

---

### 3.4. https://www.briefmenow.org/microsoft/which-code-should-you-use-52/

You have the following code:

```
List<Int32> items = new List<int> { 100, 95, 80, 75, 95 };
```

You need to retrieve all of the numbers from the items variable 
that are greater than 80. Which code should you use?

A.
```
var result = from i in items
	where i > 80
	select i;
```

B.
```
var result = from i in items
	groupby i into grouped
	where grouped.Key > 80
	select i;
```

C. ``var result = item.Take(80);``

D. ``var result = item.Skip(80);``

Answer: A

---

## 4. XML - ``XNamespace``, ``XElement``, ``XAttribute``

### 4.1 https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-311/

You are developing an application that will populate an extensive XML tree 
from a Microsoft SQL Server 2008 R2 database table named Contacts.
You are creating the XML tree. 
The solution must meet the following requirements:
Minimize memory requirements.
Maximize data processing speed.
You open the database connection. 
You need to create the XML tree.
How should you complete the relevant code? 


```

Console.WriteLine(root);

	from c in db.Contacts
	orderby c.ContactId
	select new XElement("contact",  
    	new XAttribute("ContactId", 1),  
    	new XAttribute("firstName", 2),  
    	new XAttribute("lastName", 3)
    )
);
```

* ``XElement root = new XElement("{ContactList}contacts", "content");``
* 
```
XNamespace ew = "ContactList";
XElement root = new XElement(ew + "Root");
```
* ``XAttribute contacts = new XElement``("contacts",``
* ``XElement contacts = new XElements("contacts",``

Answer: 

```
XNamespace ew = "ContactList";
XElement root = new XElement(ew + "Root");
XElement xmlTree = new XElement("contact",  
    	new XAttribute("ContactId", 1),  
    	new XAttribute("firstName", 2),  
    	new XAttribute("lastName", 3));
XAttribute contacts = new XAttribute``("contacts", 
	from c in db.Contacts
	orderby c.ContactId
	select xmlTree);
```	
---

### [XNamespace Class](https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xnamespace?view=netcore-3.1)
Namespace: ``System.Xml.Linq``
Represents an XML namespace. This class cannot be inherited.
```
public sealed class XNamespace
```

#### Remarks

This class represents the XML construct of namespaces.

Every ``XName`` contains an ``XNamespace``. 
Even if an element is not in a namespace, 
the element's ``XName`` still contains a namespace, ``XNamespace.None``. 
The ``XName.Namespace`` property is guaranteed to not be null.

#### Creating an XNamespace Object

The most common way to create an ``XNamespace`` object 
is to simply assign a string to it. 
You can then __combine the namespace with a local name__ 
by using the override of the addition operator. 
The following example shows this idiom:

```
XNamespace aw = "http://www.adventure-works.com";  
XElement root = new XElement(aw + "Root", "Content");  
Console.WriteLine(root);  
```

This example produces the following output:
```
<Root xmlns="http://www.adventure-works.com">Content</Root>
```

---
### [XElement Class](https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement?view=netcore-3.1)
Namespace: ``System.Xml.Linq``
Represents an XML element. See XElement Class Overview and 
the Remarks section on this page for usage information and examples.
```
public class XElement : System.Xml.Linq.XContainer, System.Xml.Serialization.IXmlSerializable
```

```
XElement xmlTree1 = new XElement("Root",  
    new XElement("Child1", 1),  
    new XElement("Child2", 2),  
    new XElement("Child3", 3),  
    new XElement("Child4", 4),  
    new XElement("Child5", 5),  
    new XElement("Child6", 6)  
);  

XElement xmlTree2 = new XElement("Root",  
    from el in xmlTree1.Elements()  
    where((int)el >= 3 && (int)el <= 5)  
    select el  
);  
Console.WriteLine(xmlTree2);  
```

This example produces the following output:

```
<Root>  
  <Child3>3</Child3>  
  <Child4>4</Child4>  
  <Child5>5</Child5>  
</Root>  
```

```
XNamespace aw = "http://www.adventure-works.com";  
XElement xmlTree1 = new XElement(aw + "Root",  
    new XElement(aw + "Child1", 1),  
    new XElement(aw + "Child2", 2),  
    new XElement(aw + "Child3", 3),  
    new XElement(aw + "Child4", 4),  
    new XElement(aw + "Child5", 5),  
    new XElement(aw + "Child6", 6)  
);  

XElement xmlTree2 = new XElement(aw + "Root",  
    from el in xmlTree1.Elements()  
    where((int)el >= 3 && (int)el <= 5)  
    select el  
);  
Console.WriteLine(xmlTree2);  
```

This example produces the following output:

```
<Root xmlns="http://www.adventure-works.com">  
  <Child3>3</Child3>  
  <Child4>4</Child4>  
  <Child5>5</Child5>  
</Root>  
```

---

### [XElement.Attribute(XName) Method](https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.attribute?view=netcore-3.1)
Namespace: ``System.Xml.Linq``
Returns the XAttribute of this XElement that has the specified XName.

```
public System.Xml.Linq.XAttribute Attribute (System.Xml.Linq.XName name);
```

```
XNamespace aw = "http://www.adventure-works.com";  
XElement xmlTree = new XElement(aw + "Root",  
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),  
    new XAttribute(aw + "Att", "attribute content")  
);  
XAttribute att = xmlTree.Attribute(aw + "Att");  
Console.WriteLine(att);  
```

This example produces the following output:
```
aw:Att="attribute content"
```

---
### [XAttribute Class](https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xattribute?view=netcore-3.1)
Namespace: ``System.Xml.Linq``
Represents an XML attribute.
```
public class XAttribute : System.Xml.Linq.XObject
```

```
XElement root;  

double dbl = 12.345;  
XAttribute[] attArray = {  
    new XAttribute("Att4", 1),  
    new XAttribute("Att5", 2),  
    new XAttribute("Att6", 3)  
};  
DateTime dt = new DateTime(2006, 10, 6, 12, 30, 00);  

// string content  
root = new XElement("Root",  
    new XAttribute("Att1", "Some text"),  

    // double content  
    new XAttribute("Att2", dbl),  

    // DateTime content  
    new XAttribute("Att3", dt),  

    // XAttribute array content  
    attArray  
);  

Console.WriteLine(root);  
```

This example produces the following output:
```
<Root Att1="Some text" Att2="12.345" Att3="2006-10-06T12:30:00" Att4="1" Att5="2" Att6="3" />  
```

#### Remarks
An XML attribute is a __name/value pair associated with an XML element__.

Each XElement contains a list of the attributes for that element. 
Attributes must have a qualified name that is unique to the element. 
Attributes are not derived from XNode; 
they are not nodes in the XML tree. Instead, 
they are simply name/value pairs associated with an element.

Attributes are maintained in the XML tree __in the order 
that they were added to the element__. 
When a collection of attributes is returned by Attributes, 
they are returned in the order that 
they were added to the element, and are not sorted.

Technically, in XML, namespace declarations are not attributes proper. 
However, this distinction is not normally made by many XML programmers. 
Instead, because namespace declarations 
have exactly the same XML syntax as attributes, 
most XML programmers think of namespaces as attributes. 
To simplify the LINQ to XML programming interface, 
namespaces are represented in the XML tree as attributes. 
Such namespace attributes impact serialization of an XML tree. 
When serializing, LINQ to XML attempts to serialize 
with the namespace prefix specified in namespace attributes. 
You can use the ``IsNamespaceDeclaration`` to determine 
if an attribute is really a namespace declaration.


---

# Debug / Log/ Testing

## I. Default Debug configuration.

### 1. https://www.briefmenow.org/microsoft/which-two-actions-should-you-perform-1392/

You are developing an application by using C#.
You have the following requirements:
Support 32-bit and 64-bit system configurations.
Include pre-processor directives that are specific to the system configuration.
Deploy an application version that includes both system configurations to testers.
Ensure that stack traces include accurate line numbers.
You need to configure the project to avoid changing individual configuration settings every time 
you deploy the application to testers.
Which two actions should you perform? (Each correct answer presents part of the solution.
Choose two.)

A.
Update the platform target and conditional compilation symbols for each application configuration.

B.
Create two application configurations based on the default Release configuration.

C.
Optimize the application through address rebasing in the 64-bit configuration.

D.
Create two application configurations based on the default Debug configuration.

---

Answer:
Create two application configurations based on the default Release configuration.
Create two application configurations based on the default Debug configuration.

[Set debug and release configurations in Visual Studio](https://docs.microsoft.com/zh-tw/visualstudio/debugger/how-to-set-debug-and-release-configurations?view=vs-2019)
[Understand build configurations](https://docs.microsoft.com/zh-tw/visualstudio/ide/understanding-build-configurations?view=vs-2019)

---

## II.

### 1. https://www.briefmenow.org/microsoft/what-are-two-possible-ways-to-achieve-this-goal-278/

You are testing an application. 
The application includes methods named ``CalculateInterest`` and ``LogLine``. 
The ``CalculateInterest()`` method calculates loan interest. 
The ``LogLine()`` method sends diagnostic messages to a console window.
The following code implements the methods. 

```
private static decimal CalculateInterest(decimal loanAmount, int loadTerm, decimal loadRate) {
    decimal interestAmount = loanAmount * loadRate * loadTerm;
    
    LogLine("Interest Amount: " + interestAmount.ToString("c"));

    return interestAmount;
}

private static void LogLine(string message, string detail) {
    Console.WriteLine("Log: {0} = {1}", message, detail);    
}
```

You have the following requirements:
The ``Calculatelnterest(`` method must run __for all build configurations__.
The ``LogLine()`` method must run __only for debug builds__.
You need to ensure that the methods run correctly.
What are two possible ways to achieve this goal? 

A.
Insert the following code segment at line 01:
``#region DEBUG``
Insert the following code segment at line 10:
``#endregion``

B.
Insert the following code segment at line 10:
``[Conditional("DEBUG")]``

C.
Insert the following code segment at line 05:
``#region DEBUG``
Insert the following code segment at line 07:
``#endregion``

D.
Insert the following code segment at line 01:
``#if DE30G``
Insert the following code segment at line 10:
``#endif``

E.
Insert the following code segment at line 01:
``[Conditional("DEBUG")]``

F.
Insert the following code segment at line 05:
``#if DEBUG``
Insert the following code segment at line 07:
``#endif``

G.
Insert the following code segment at line 10:
``[Conditional("RELEASE")]``

Answer: BF

```
[Conditional("DEBUG")]
private static void LogLine(string message, string detail) {
    Console.WriteLine("Log: {0} = {1}", message, detail);    
}
```
or
```
#if DEBUG
LogLine("Interest Amount: " + interestAmount.ToString("c"));
#endif
```

* ``#if DEBUG``: 
The code in here won’t even reach the IL on release.
* ``[Conditional("DEBUG")]``: 
This code will reach the IL, however the calls to the method 
will not execute unless ``DEBUG`` is on.
http://stackoverflow.com/questions/3788605/if-debug-vs-conditionaldebug

---

### 2. https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-305/

You are testing an application. 
The application includes methods named ``CalculateInterest`` and ``LogLine``. 
The ``CalculateInterest()`` method calculates loan interest. 
The ``LogLine()`` method sends diagnostic messages to a console window.

```
private static decimal CalculateInterest(decimal loanAmount, int loadTerm, decimal loadRate) {
    decimal interestAmount = loanAmount * loadRate * loadTerm;
    
    LogLine("Interest Amount: " + interestAmount.ToString("c"));

    return interestAmount;
}

private static void LogLine(string message, string detail) {
    Console.WriteLine("Log: {0} = {1}", message, detail);    
}
```

You have the following requirements:
The ``CalculateInterest()`` method must run __for all build configurations__.
The ``LogLine()`` method must be called __only for debug builds__.
You need to ensure that the methods run correctly.

How should you complete the relevant code? 

* ``[Conditional("DEBUG")]``
* ``[Conditional("RELEASE")]``
* ``#if DEBUG``
* ``#region DEBUG``
* ``#endif``
* ``#endregion``

Answer:
```
#if DEBUG
LogLine("Interest Amount: " + interestAmount.ToString("c"));
#endif
```

---

### 3. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1240/

You are developing an application that will process orders. 
The debug and release versions of the application
will display different logo images.
You need to ensure that the correct image path is set based on the build configuration.
Which code segment should you use?

A.
```
#if (DEBUG)
	imgPath = "TempFolder/Images/";
#elif (RELEASE)
	imgPath = "TempFolder/Images/";
#endif
```

B.
```
if (DEBUG)
	imgPath = "TempFolder/Images/";
else
	imgPath = "TempFolder/Images/";
endif
```

C.
```
#if (DEBUG)
	imgPath = "TempFolder/Images/";
#else
	imgPath = "TempFolder/Images/";
#endif
```

D.
```
if (Debugger.IsAttached) {
	imgPath = "TempFolder/Images/";
} else {
	imgPath = "DevFolder/Images/";
}
```

Answer: C

Explanation:
There is no such constraint (unless you define one explicitly) ``RELEASE``.
[Will #if RELEASE work like #if DEBUG does in C#?](http://stackoverflow.com/questions/507704/will-if-release-work-like-if-debug-does-in-c)

``RELEASE`` is not defined, but you can use

```
#if (!DEBUG)
  ...
#endif
```

---

### 4. https://www.briefmenow.org/microsoft/you-need-to-use-different-databases-during-the-developm-2/

You are creating an application that reads from a database.
You need to use different databases during the development phase 
and the testing phase by using conditional compilation techniques.
What should you do?

A.
Configure the assembly metadata to use the pre-existing public key 
for the assembly identity by using the ``AssemblySignatureKeyAttribute`` attribute.

B.
Disable the strong-name bypass feature of Microsoft .NET Framework in the registry.

C.
Configure the Define DEBUG constant setting in Microsoft Visual Studio.

D.
Decorate the code by using the [assembly:AssemblyDelaySignAttribute(true)] attribute.

Answer: C.


### [AssemblySignatureKeyAttribute](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assemblysignaturekeyattribute?view=netcore-3.1)
Provides migration from an older, simpler strong name key to a larger key with a stronger hashing algorithm.

hash 算法

### [How to: Disable the Strong-Name Bypass Feature](https://github.com/fiyazbinhasan/docs-1/blob/master/docs/framework/app-domains/how-to-disable-the-strong-name-bypass-feature.md)

加密相關

### [AssemblyDelaySignAttribute Class](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assemblydelaysignattribute?view=netcore-3.1)
Specifies that the assembly is not fully signed when created.

---

### 5. ## https://www.briefmenow.org/microsoft/you-need-to-ensure-that-enough-debugging-information-is-2/

You are developing an application that produces an executable named ``MyApp.exe`` 
and an assembly named ``MyApp.dll``.
The application will be sold to several customers.
You need to ensure that enough debugging information is available for  ``MyApp.exe``, 
so that if the application throws an error in a customer’s environment, 
you can debug the error in your own development environment.
What should you do?


A.
Digitally sign ``MyApp.dll``.

B.
Produce program database (PDB) information when you compile the code.

C.
Compile MyApp.exe by using the /unsafe compiler option.

D.
Initializes a new instance of the ``AssemblyDelaySignAttribute`` class in the ``MyApp.dll`` constructor.

Answer: B

* [What is the usage of pdb's (Program Debug DataBase)?](https://stackoverflow.com/questions/1449060/what-is-the-usage-of-pdbs-program-debug-database)
* [/PDB (Use Program Database)](https://docs.microsoft.com/en-us/cpp/build/reference/pdb-use-program-database?view=msvc-160)

---

## III. EventLogTraceListener

### 1. https://www.briefmenow.org/microsoft/what-should-you-include-in-the-application-code-8/


You are developing an application that uses a ``.config`` file.
The relevant portion of the ``.config`` file is shown as follows:

```

<system.diagnostics>
  <trace autoflush="false" indentsize="0">
    <listeners>
      <add name="appListener" 
          type="System.Diagnostics.EventLogTraceListener"  
          initializeData="TraceListenerLog" />  
    </listeners>
  </trace>
</system.diagnostics>
```

You need to ensure that diagnostic data for the application 
writes to the event tog by using the configuration specified in the ``.config`` file.
What should you include in the application code?

A.
```
EventLog log = new EventLog();
log.WriteEntry("Trace data...");
```

B. ``Debug.WriteLine("Trace data...");``

C.
```
Console.SetOut(new StreamWrite("System.Diagnostics.EventLogTraceListener"));
Console.WriteLine("Trace data...");
```

D. ``Trace.WriteLine("Trace data...");``

Answer: D.

---

### [EventLogTraceListener Class](https://docs.microsoft.com/zh-tw/dotnet/api/system.diagnostics.eventlogtracelistener?view=netcore-3.1)

Provides a simple listener that directs tracing or debugging output to an [EventLog](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.eventlog?view=netcore-3.1).

```
public static void Main(string[] args) {

    // Create a trace listener for the event log.
    EventLogTraceListener myTraceListener = new EventLogTraceListener("myEventLogSource");

    // Add the event log trace listener to the collection.
    Trace.Listeners.Add(myTraceListener);

    // Write output to the event log.
    Trace.WriteLine("Test output");
 }
```

```

<configuration>  
  <system.diagnostics>  
    <trace autoflush="false" indentsize="4">  
      <listeners>  
        <add name="myListener"  
          type="System.Diagnostics.EventLogTraceListener"  
          initializeData="TraceListenerLog" />  
      </listeners>  
    </trace>  
  </system.diagnostics>  
</configuration>  
```

---

## IV. Difference between ``Trace.Assert()`` and ``Debug.Assert()``

### 1. 

You are debugging an application that calculates loan interest. 
The application includes the following code.

```
private static decimal CalculateInterest(decimal loanAmount, int loadTerm, decimal loadRate) {
    decimal interestAmount = loanAmount * loadRate * loadTerm;
    
    return interestAmount;
}
```

A.
Insert the following code segment at line 03:
``Trace.Assert(loanAmount > 0);``

B.
Insert the following code segment at line 03:
``Debug.Assert(loanAmount > 0);``

C.
Insert the following code segment at line 05:
``Debug.Write(loanAmount > 0);``

D.
Insert the following code segment at line 05:
``Trace.Write(loanAmount > 0);``

---

By default, the ``Debug.Assert`` method works only in debug builds. 
Use the ``Trace.Assert`` method 
if you want to do assertions in release builds. 
http://msdn.microsoft.com/en-us/library/kssw4w7z.aspx

---

### 2. https://www.briefmenow.org/microsoft/you-need-to-meet-the-requirements-29/

You are debugging an application that calculates loan interest. 
The application includes the following code.

```
private static decimal CalculateInterest(decimal loanAmount, int loadTerm, decimal loadRate) {
    decimal interestAmount = loanAmount * loadRate * loadTerm;
    
    return interestAmount;
}
```

You have the following requirements:
The debugger must break execution within the ``Calculatelnterest()`` method 
when the ``loanAmount`` variable is __less than or equal to zero__.
__The release version of the code must not be impacted by any changes__.
You need to meet the requirements. What should you do?

A.
Insert the following code segment at tine 05:
``Debug.Write(loanAmount > 0);``

B.
Insert the following code segment at line 05:
``Trace.Write(loanAmount > 0);``

C.
Insert the following code segment at line 03:
``Debug.Assert(loanAmount > 0);``

D.
Insert the following code segment at line 03:
``Trace.Assert(loanAmount > 0);``

Answer: C

---

# Performance counter / monitoring

## 1. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-16-19/

You are developing a method named ``CreateCounters`` that 
will create performance counters for an application.
The method includes the following code. 

```
void CreateCounters() {
    if (!PerformanceCounterCategory.Exists("Contoso")) {
        var counters = new CounterCreationDataCollection();
        var ccdCounter1 = new CounterCreationData {
            CounterName = "Counter1",
            CounterType = PerformanceCounterType.SampleFraction
        };
        counters.Add(ccdCounter1);
        var ccdCounter2 = new CounterCreationData {
            CounterName = "Counter2",
        };
        counters.Add(ccdCounter2);
        PerformanceCounterCategory.Create(
            "Contoso", "Help string", PerformanceCounterCategoryType.MultiInstance, counters);
    }
}
```

You need to ensure that ``Counter1`` is 
__available for use in Windows Performance Monitor (PerfMon)__.
Which code segment should you insert at line 16?

A. ``CounterType = PerformanccCounterType.RawBase``

B. ``CounterType = PerformanceCounterType.AverageBase``

C. ``CounterType = PerformanceCounterType.SampleBase``

D. ``CounterType = PerformanceCounterType.CounterMultiBase``

---

Answer:
CounterType = PerformanceCounterType.SampleBase

https://stackoverflow.com/questions/28441713/select-performancecountertype/28443243

[PerformanceCounterType Enum](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.performancecountertype?redirectedfrom=MSDN&view=netcore-3.1)
Namespace: System.Diagnostics
Specifies the formula used to calculate the NextValue() method for a PerformanceCounter instance.

``RawBase``
A base counter that stores the denominator of a counter that 
presents a general arithmetic fraction. 
Check that this value is greater than zero 
before using it as the denominator in a RawFraction value calculation.
* ``AverageBase``:
A base counter that is used in the calculation of time or count averages, 
such as AverageTimer32 and AverageCount64.
 Stores the denominator for calculating a counter 
 to present "time per operation" or "count per operation".
* ``AverageTimer32``
An average counter that measures the time it takes, on average, to complete a process or operation. Counters of this type display a ratio of the total elapsed time of the sample interval to the number of processes or operations completed during that time. This counter type measures time in ticks of the system clock. Counters of this type include PhysicalDisk\ Avg. Disk sec/Transfer.
* ``CounterMultiBase``
A base counter that indicates the number of items sampled. 
It is used as the denominator in the calculations 
to get an average among the items sampled when taking timings of multiple, 
but similar items. Used with CounterMultiTimer, CounterMultiTimerInverse, 
CounterMultiTimer100Ns, and CounterMultiTimer100NsInverse.
* ``SampleBase``
A base counter that stores the number of sampling interrupts taken
and is used as a denominator in the sampling fraction. 
The sampling fraction is the number of samples that were 1 (or true) for a sample interrupt. 
Check that this value is greater than zero 
before using it as thedenominator in a calculation of SampleFraction.
* ``SampleFraction`` – A percentage counter that shows the average ratio of hits to all
operations during the last two sample intervals. Formula: ((N 1 – N 0) / (D 1 – D 0)) x 100, where the numerator
represents the number of successful operations during the last sample interval, and the denominator
represents the change in the number of all operations (of the type measured) completed during the sample
interval, using counters of type SampleBase. Counters of this type include Cache\\Pin Read Hits %.


http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecountertype.aspx

---

## 2. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-16-20/

You are developing a method named ``CreateCounters`` that 
will create performance counters for an application.
The method includes the following code. 


```
void CreateCounters() {
    if (!PerformanceCounterCategory.Exists("Contoso")) {
        var counters = new CounterCreationDataCollection();
        var ccdCounter1 = new CounterCreationData {
            CounterName = "Counter1",
            CounterType = PerformanceCounterType.AverageTimer32
        };
        counters.Add(ccdCounter1);
        var ccdCounter2 = new CounterCreationData {
            CounterName = "Counter2",
        };
        counters.Add(ccdCounter2);
        PerformanceCounterCategory.Create(
            "Contoso", "Help string", PerformanceCounterCategoryType.MultiInstance, counters);
    }
}
```

You need to ensure that ``Counter2`` is available 
for use in Windows Performance Monitor (PerfMon).
Which code segment should you insert at line 16?

A. ``CounterType = PerformanceCounterType.RawBase``

B. ``CounterType = PerformanceCounterType.AverageBase``

C. ``CounterType = PerformanceCounterType.SampleBase``

D. ``CounterType = PerformanceCounterType.CounterMultiBase``

Answer: D

---

## 1. https://www.briefmenow.org/microsoft/which-three-actions-should-you-perform-in-sequence-881/

You are developing an application by using C#. 
The application will process several objects per second.
You need to create a performance counter to analyze the object processing.
Which three actions should you perform in sequence? 


* Add the ``CounterCreationData`` objects to the collection by calling the ``Add()`` method of the collection
* Create a ``PerformanceCounterPermissionEntryCollection`` collection.
* Call the ``Create()`` method of the ``PerformanceCounterCategory`` class and pass the collection to the method
* Get the ``CatetoryName`` property of the ``PerformanceCounterPermissionEntry`` class
* Create a ``CounterCreationDataCollection`` collection.
Then create the ``counters`` as ``CounterCreationData`` objects and set the necessary properties

---

Answer:
1. Create a ``CounterCreationDataCollection`` collection.
Then create the ``counters`` as ``CounterCreationData`` objects and set the necessary properties
2. Add the ``CounterCreationData`` objects to the collection by calling the ``Add()`` method of the collection
3. Call the ``Create()`` method of the ``PerformanceCounterCategory`` class and pass the collection to the method

### [PerformanceCounter Class](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.performancecounter?view=netcore-3.1)

Namespace: ``System.Diagnostics``

---

## 2. https://www.briefmenow.org/microsoft/which-three-actions-should-you-perform-in-sequence-882/
 
You are developing an application by using C#.
The application will process several objects per second.
You need to create a performance counter to analyze the object processing.
Which three actions should you perform in sequence?

* Add the ``PerformanceCounterPermissionEntry`` objects to the collection by calling the ``Add()`` method of the collection
* Add the ``CounterCreationData`` objects to the collection by calling the ``Add()`` method of the collection
* Create a ``CounterCreationDataCollection`` collection. Then create the ``counters` as ``CounterCreationData`` objects and set the necessary properties
* Create a ``PerformanceCounterPermissionEntryCollection`` collection.
* Call the ``Create()`` method of the ``PerformanceCounterCategory`` class and pass the collection to the method
* Get the ``CatetoryName`` property of the ``PerformanceCounterPermissionEntry`` class

---

Answer:

* Create a ``CounterCreationDataCollection`` collection. Then create the ``counters` as ``CounterCreationData`` objects and set the necessary properties
* Add the ``CounterCreationData`` objects to the collection by calling the ``Add()`` method of the collection
* Call the ``Create()`` method of the ``PerformanceCounterCategory`` class and pass the collection to the method


---

# garbage collector

## 1. https://www.briefmenow.org/microsoft/which-garbage-collector-method-should-you-use-14/

You are developing an application by using C#.
The application includes an object that performs a long running process.
You need to ensure that the garbage collector 
does not release the object’s resources until the process completes.
Which garbage collector method should you use?

A. ``WaitForFullGCComplete()``

B. ``WaitForFullGCApproach()``

C. ``KeepAlive()``

D. ``WaitForPendingFinalizers()``

Answer: C


The GC.KeepAlive method references the specified object, which makes it ineligible for garbage collection from
the start of the current routine to the point where this method is called.
The purpose of the KeepAlive method is to ensure the existence of a reference to an object that is at risk of
being prematurely reclaimed by the garbage collector.
The KeepAlive method performs no operation and produces no side effects other than extending the lifetime of
the object passed in as a parameter.

---

## 2

You are developing an application by using C#.
The application includes an object that performs a long running process.
You need to ensure that the garbage collector 
does not release the object’s resources until the process completes.
Which garbage collector method should you use?

A. ``ReRegisterForFinalize()``
Requests that the system call the finalizer for the specified object for which SuppressFinalize(Object) has previously been called.

B. ``SuppressFinalize()``
Requests that the common language runtime not call the finalizer for the specified object.

C. ``Collect()``
Forces an immediate garbage collection of all generations.

D. ``WaitForFullGCApproach()``
Returns the status of a registered notification for 
determining whether a full, blocking garbage collection 
by the common language runtime is imminent.

Answer: B

---

## 3. https://www.briefmenow.org/microsoft/which-garbage-collector-method-should-you-use-16/

You are developing an application by using C#.
The application includes an object that performs a long running process.
You need to ensure that the garbage collector __does not release 
the object’s resources until the process completes__.
Which garbage collector method should you use?

A. ``WaitForFullGCComplete()``
B. ``SuppressFinalize()``
C. ``WaitForFullGCApproach()``
D. ``WaitForPendingFinalizers()``

Answer: B

---

## 4. https://www.briefmenow.org/microsoft/which-garbage-collector-method-should-you-use-17/

You are developing an application by using C#.
The application includes an object that performs a long running process.
You need to ensure that the garbage collector
does not release the object’s resources until the process completes.
Which garbage collector method should you use?


A. ``RemoveMemoryPressure()``
B. ``ReRegisterForFinalize()``
C. ``WaitForFullGCComplete()``
D. ``KeepAlive()``

Answer: D

---

## 5. ``WeakReference``

### 1. https://www.briefmenow.org/microsoft/which-code-should-you-insert-at-line-03-21/

You are creating a class named ``Data`` that includes a dictionary object named ``_data``.
You need to allow the garbage collection process 
to collect the references of the ``_data`` object.
How should you complete the relevant code? 

```
public class Data {
	
	public Data(int count) {
		for (int i = 0; i < count; i++) {

		}
	}
}
```

* ``static Dictionary<int, WeakReference>() _data;``
* ``static Dictionary<int, Int32>() _data;``
* ``_data.Add(i, new WeakReference(new Class((i * 2), false);``
* ``_data.Add(i, (Int32)(i * 2));``

Answer:

```
public class Data {
	static Dictionary<int, WeakReference>() _data;
	public Data(int count) {
		for (int i = 0; i < count; i++) {
			`_data.Add(i, new WeakReference(new Data((i * 2), false);
		}
	}
}
```

---



---
