# C# Exam Questions 70-483 Reading - Syntax - Part 1
###### 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/
---
[Link Part 2](https://hackmd.io/@sfRJH1u7S464tSaizL7ZsQ/ry-bw7Xav)
---
# switch
## 1.
You are implementing a library method that
accepts a ``character`` parameter and returns a ``string``.
If the lookup succeeds, the method must return the corresponding ``string`` value.
If the lookup fails, the methodmust return the value “invalid choice.”
You need to implement the lookup algorithm.
How should you complete the relevant code?
```
public string GetResponse(char letter) {
string response;
switch (letter) {
case 'a':
response = "animal";
break;
case 'm':
response = "mineral";
break;
default:
response = "invalid choice";
break;
}
return response;
}
```
---
## 2. https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-314/
You are adding a function to a membership tracking application.
The function uses an integer named ``memberCode`` as an input parameter
and returns the ``memberType`` as a ``string``.
The function must meet the following requirements:
Return ``Non-Member`` if the ``memberCode`` is 0.
Return ``Member`` if the ``memberCode`` is 1.
Return ``Invalid`` if the ``memberCode`` is any value other than 0 or 1.
You need to implement the function to meet the requirements.
How should you complete the relevant code?
* ``default``
* ``switch``
* ``break``
* ``case``
```
private string GetMemberType(int memberCode) {
string memberType;
[] (memberCode) {
[] 0:
memberType = "Non-Member";
[];
[] 1:
memberType = "Non-Member";
[];
[]:
memberType = "Non-Member";
[];
}
}
```
Answer:
```
private string GetMemberType(int memberCode) {
string memberType;
switch (memberCode) {
case 0:
memberType = "Non-Member";
break;
case 1:
memberType = "Member";
break;
default:
memberType = "Invalid";
break;
}
}
```
---
## 3. https://www.briefmenow.org/microsoft/you-need-to-ensure-that-the-method-meets-the-following/
You have a method that will evaluate a parameter of type ``Int32`` named ``status``.
You need to ensure that the method meets the following requirements:
If ``Status`` is set to ``Active``, the method must return ``1``.
If ``Status`` is set to ``Inactive``, the method must return ``0``.
If ``Status`` is any other value, the method must return ``-1``.
What should you do?
```
Int32 returnValue = Int32.MinValue;
switch(status) {
[]
returnValue = 1;
[]
[]
returnValue = 0;
[]
[]
returnValue = -1;
[]
}
return returnValue;
```
* ``break;``
* ``case "Active":``
* ``case "Inactive":``
* ``default:``
* ``goto default``
* ``return``
Answer:
```
Int32 returnValue = Int32.MinValue;
switch(status) {
case "Active":
returnValue = 1;
break;
case "Inactive":
returnValue = 0;
break;
default:
returnValue = -1;
break;
}
return returnValue;
```
---
## 4. https://www.briefmenow.org/microsoft/hot-area-87/
You are building a data access layer in an application that contains the following code:
```
public static Object GetTypeDefault(DbType dbDataType) {
switch (dbDataType) {
case DbType.Boolean:
return false;
case DbType.DateTime:
return DateTime.MinValue;
case DbType.Decimal:
return 0m;
case DbType.Int32:
return 0;
case DbType.String:
return String.Empty;
default:
return null;
}
}
```
For each of the following statements,
select Yes if the statement is true. Otherwise, select No.
* If ``dbDataType`` is ``DateTime``, today's date is returned.
-> No
* If ``dbDataType`` is ``Int64``, ``Null`` is returned.
-> Yes
* If ``dbDataType`` is ``Double``, ``0`` is returned.
-> No
---
# Enum
## 1. https://www.briefmenow.org/microsoft/hot-area-83/
You are reviewing the following code:
```
[EmailAddressAttribute]
public enum Group {
Users = 1,
Supervisors = 2,
Managers = 4,
Administrators = 8
}
public class User {
public Group UserGroup { get; set; }
}
```
For each of the following statements,
select Yes if the statement is true. Otherwise, select No.
* A user can be a member of more than one of the groups.
--> No
* If the user belongs to only the Administrators group,
the following code will return a value of true
```
user.UserGroup == Group.Administrators
```
--> Yes
* If the user belongs to only the Supervisors group,
the following code will return a value of true
```
user.UserGroup It; Group.Administrators
```
--> No
---
# Collection
## 1.
You are developing an application that includes a class named ``Order``.
The application will store a collection of ``Order`` objects.
The collection must meet the following requirements:
Use strongly typed members.
Process Order objects in first-in-first-out order.
Store values for each Order object.
Use zero-based indices.
You need to use a collection type that meets the requirements.
Which collection type should you use?
Queue<T>: first-in-first-out order
---
## 2. https://www.briefmenow.org/microsoft/which-type-of-collection-should-you-use-6/
You need to store the values in a collection.
The solution must meet the following requirements:
The values must be stored in the order that they were added to the collection.
The values must be accessed in a first-in, first-out order.
Which type of collection should you use?
A. ``SortedList``
B. ``Queue``
C. ``ArrayList``
D. ``Hashtable``
Queue: first-in, first-out order
---
## 3. https://www.briefmenow.org/microsoft/which-collection-type-should-you-use-11/
You are developing an application that includes a class named ``Order``.
The application will store __a collection of ``Order`` objects__.
The collection must meet the following requirements:
__Internally store a key and a value for each collection item__.
Provide objects to __iterators__ in __ascending order__
based on the ``key.Ensure`` that item are accessible by zero-based index or by key.
You need to use a collection type that meets the requirements.
Which collection type should you use?
A. ``LinkedList``
B. ``Queue``
C. ``Array``
D. ``HashTable``
E. ``SortedList``
Answer: E
### [LinkedList<T> Class](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=netcore-3.1)
* Represents a doubly linked list.
* Namespace: ``System.Collections.generic``
```
public class LinkedList<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
```
### [Queue<T> Class](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1?view=netcore-3.1)
* Represents a first-in, first-out collection of objects.
* Namespace: ``System.Collections.Generic``
```
public class Queue<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection
```
### [Hashtable Class](https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable?view=netcore-3.1)
* Represents a collection of key/value pairs that are organized based on the hash code of the key.
* Namespace: ``System.Collections``
```
public class Hashtable : ICloneable, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
```
### [SortedList<TKey,TValue> Class](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2?view=netcore-3.1)
* Represents a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.
* Namespace: ``System.Collections.Generic``
```
public class SortedList<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IDictionary<TKey,TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>, System.Collections.IDictionary
```
有 key / value 的 collection 只有 ``SortedList`` 和 ``Hashtable``
但 ``SortedList`` 會自動幫資料以 key 以 ascending order 排序,但 ``Hashtable`` 則沒有
```
Hashtable openWith = new Hashtable();
openWith.Add("EEE", "Eggplant");
openWith.Add("III", "illusion");
openWith.Add("AAA", "Alice");
openWith.Add("RRR", "Roll out");
ICollection keyColl = openWith.Keys;
foreach(string s in keyColl) {
Console.WriteLine("Foreach Key = {0}", s);
}
```
output:
>Foreach Key = AAA
Foreach Key = RRR
Foreach Key = EEE
Foreach Key = III
```
SortedList<string, string> openWith = new SortedList<string, string>();
openWith.Add("EEE", "Eggplant");
openWith.Add("III", "illusion");
openWith.Add("AAA", "Alice");
openWith.Add("RRR", "Roll out");
IList<string> ilistKeys = openWith.Keys;
foreach(string s in ilistKeys) {
Console.WriteLine("foreach Key = {0}", s);
}
```
output:
>foreach Key = AAA
foreach Key = EEE
foreach Key = III
foreach Key = RRR
---
### 4. https://www.briefmenow.org/microsoft/you-need-to-ensure-that-the-method-extracts-a-list-of-u-4/
You write the following method (line numbers are included for reference only):
```
public static List<string> TestIfWebSite(string url) {
const string pattern = @"http://(www\\.)?([^\.]+)\.com";
List<string> result = new List<string>();
[]
MatchCollection myMatches = Regex.Matches(url, pattern);
...
return result;
}
```
You need to ensure that the method extracts a list of URLs
that match the following pattern:
``@http://(www\\.)?([^\\.]+)\\.com;``
Which code should you insert at line 07?
A. ``result = (List<string>) myMatches.SyncRoot;``
B.
```
result = (from System.Text.RegularExpressions.Match m in myMatches
where m.Value.Contains(pattern)
select m.Value)
.ToList<string>();
```
C.
```
foreach(Match currentMatch in myMatches)
result.Add(currentMatch.Groups.ToString());
```
D.
```
foreach(Match currentMatch in myMatches)
result.Add(currentMatch.Value);
```
Answer: D
---
### [MatchCollection Class](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.matchcollection?view=netcore-3.1)
* Namespace: System.Text.RegularExpressions
* Represents the set of successful matches found by
iteratively applying a regular expression pattern to the input string.
__The collection is immutable (read-only) and has no public constructor__.
The [``Matches(String)``](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.matches?view=netcore-3.1#System_Text_RegularExpressions_Regex_Matches_System_String_) method returns a ``MatchCollection`` object.
```
using System;
using System.Text.RegularExpressions;
public class Test {
public static void Main () {
// Define a regular expression for repeated words.
Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Define a test string.
string text = "The the quick brown fox fox jumps over the lazy dog dog.";
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
Console.WriteLine("{0} matches found in:\n {1}",
matches.Count,
text);
// Report on each match.
foreach (Match match in matches) {
GroupCollection groups = match.Groups;
Console.WriteLine("'{0}' repeated at positions {1} and {2}",
groups["word"].Value,
groups[0].Index,
groups[1].Index);
}
}
}
// The example produces the following output to the console:
// 3 matches found in:
// The the quick brown fox fox jumps over the lazy dog dog.
// 'The' repeated at positions 0 and 4
// 'fox' repeated at positions 20 and 25
// 'dog' repeated at positions 50 and 54
```
``List<T>`` is mutable
### [ICollection.SyncRoot Property](https://docs.microsoft.com/en-us/dotnet/api/system.collections.icollection.syncroot?view=netcore-3.1)
* Namespace: ``System.Collections``
* Gets an object that can be used to synchronize access to the ``ICollection``.
```
public object SyncRoot { get; }
```
```
ICollection myCollection = someCollection;
lock(myCollection.SyncRoot) {
// Some operation on the collection, which is now thread safe.
foreach (object item in myCollection) {
// Insert your code here.
}
}
```
### [List<T>.ICollection.SyncRoot Property](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.system-collections-icollection-syncroot?view=netcore-3.1)
* Namespace: ``System.Collections.Generic``
* Gets an object that can be used to synchronize access to the ``ICollection``.
---
## Dictionary
### 1. https://www.briefmenow.org/microsoft/hot-area-84/
You have the following code:
```
private static Dictionary<string, int> CreateTestData() {
Dictionary<string, int> dict = new Dictionary<string, int>() {
{"Accounting", 1},
{"Marketing", 2},
{"Operations", 3},
};
return dict;
}
private static bool? FindInList(string searchTerm) {
Dictionary<string, int> dict = CreateTestData();
if (data.ContainKey(searchTerm)) { return true; }
else { return false;}
}
```
To answer, complete each statement according to the information presented in the code.
* If the searchTerm is set to "Finance", the result will be ...
-> ``false``;
* If the searchTerm is set to "1", the result will be ...
-> ``false``;
* If the searchTerm is set to "Operations", the result will be ...
-> ``true``;
---
```
bool ContainsKey(TKey key);
```
throw ``System.ArgumentNullException`` if ``key`` is null.
---
## Usage of Indexer
### 1. https://www.briefmenow.org/microsoft/you-need-to-ensure-that-the-unit-test-will-pass-9/
You are developing a class named ``Scorecard``.
The following code implements the ``Scorecard`` class.
```
public class Scorecard {
private Dictionary<string, int> players = new Dictionary<string, int>();
public void Add(string name, int score) {
players.Add(name, score);
}
[]
}
```
You create the following __unit test method__ to test the ``Scorecard`` class implementation:
```
[TestMethod]
public void UnitTest1() {
Scorecard scorecard = new Scorecard();
scorecard.Add("Player1", 10);
scorecard.Add("Player2", 15);
int expectedScore = 15;
int actualScore = scorecard["Player2"];
Assert.AreEqual(expectedScore, actualScore);
}
```
You need to ensure that the unit test will pass. What should you do?
A. Insert the following code segment at line 08:
```
public int this[string name] {
get { return players[name];}
}
```
B. Insert the following code segment at line 08:
```
public Dictionary<string, int> Players {
get { players; }
}
```
C. Replace line 03 with the following code segment:
```
public Dictionary<string, int> Players = new Dictionary<string, int>();
```
D. Insert the following code segment at line 08:
```
public int score(string name) {
return players[name];
}
```
Answer: A
好特別的用法
```
public int this[string name] {
get { return players[name];}
}
```
---
### 2. https://www.briefmenow.org/microsoft/you-need-to-ensure-that-the-unit-test-will-pass-10/
You are developing a class named EmployeeRoster. The following code implements the EmployeeRoster
class. (Line numbers are included for reference only.)
You are developing a class named ``EmployeeRoster``.
The following code implements the ``EmployeeRoster`` class.
```
public class EmployeeRoster {
private Dictionary<string, int> employees = new Dictionary<string, int>();
public void Add(string name, int salary) {
employees.Add(name, salary);
}
[]
}
```
You create the following __unit test method__ to test the ``EmployeeRoster`` class implementation:
```
public void UnitTest1() {
EmployeeRoster employeeRoster = new EmployeeRoster();
employeeRoster.Add("David Jones", 50000);
employeeRoster.Add("PHyllis Harris", 75000);
int expectedSalary = 15;
int actualSalary = employeeRoster["PHyllis Harris"];
Assert.AreEqual(expectedSalary, actualSalary);
}
```
You need to ensure that the unit test will pass. What should you do?
A. Insert the following code segment at line 08:
```
public Dictionary<string, int> Employees {
get { employees; }
}
```
B. Insert the following code segment at line 08:
```
public int this[string name] {
get { return employees[name];}
}
```
C. Replace line 03 with the following code segment:
```
public Dictionary<string, int> Employees = new Dictionary<string, int>();
```
D. Insert the following code segment at line 08:
```
public int salary(string name) {
return employees[name];
}
```
Answer B.
---
# Accessors / member access modifier
## 1
An application includes a class named ``Person``.
The ``Person`` class includes a method named ``GetData``.
You need to ensure that the ``GetData()`` from the ``Person`` class.
Which access modifier should you use for the ``GetData()`` method?
``protected`` – The type or member can be accessed only by code in the same class or structure, or in a class that
is derived from that class.
http://msdn.microsoft.com/en-us/library/ms173121.aspx
The ``protected`` keyword is a member access modifier. A protected member is accessible within its class and by
derived class instances.
---
## properties
### 1.
You are creating a class named ``Employee``.
The class exposes a ``string`` property named ``EmployeeType``.
The following code segment defines the ``Employee`` class.
```
public class Employee {
internal string EmployeeType { get; set; }
}
```
The ``EmployeeType`` property value must be accessed and modified
only by code within the ``Employee`` class or
within a class derived from the Employee class.
You need to ensure that the implementation of the ``EmployeeType`` property meets the requirements.
```
public class Employee {
protected string EmployeeType { get; private set; }
}
```
### [``protected``](https://docs.microsoft.com/en-ca/dotnet/csharp/language-reference/keywords/protected)
A ``protected`` member is accessible within its class and by derived class instances.
---
## 2. https://www.briefmenow.org/microsoft/which-two-actions-should-you-perform-1394/
You are creating a class named ``Employee``.
The class exposes a ``string`` property named ``EmployeeType``.
The following code segment defines the ``Employee`` class.
```
public class Employee {
internal string EmployeeType { get; set; }
}
```
The ``EmployeeType`` property value must meet the following requirements:
The value must be accessed only by code within the ``Employee`` class
or within a class derived from the ``Employee`` class.
The value must be modified only by code within the ``Employee`` class.
You need to ensure that the implementation of the ``EmployeeType`` property meets the requirements.
Which two actions should you perform?
A.
Replace line 03 with the following code segment:
``public string EmployeeType``
B.
Replace line 06 with the following code segment:
``protected set;``
C.
Replace line 05 with the following code segment:
``private get;``
D.
Replace line 05 with the following code segment:
``protected get;``
E.
Replace line 03 with the following code segment:
``protected string EmployeeType``
F.
Replace line 06 with the following code segment:
``private set;``
Answer: EF
---
## 3. https://www.briefmenow.org/microsoft/which-access-modifier-should-you-use-for-the-getdata-4/
An application includes a class named ``Person``.
The ``Person`` class includes a method named ``GetData``.
You need to ensure that the ``GetData()`` method
can be __used only by the ``Person`` class__ and
__not__ by any class derived from the Person class.
Which access modifier should you use for the ``GetData()`` method?
A. ``public``
B. ``protected internal``
C. ``internal``
D. ``private``
E. ``protected``
Answer: D
---
## 4. https://www.briefmenow.org/microsoft/hot-area-88/
You have the following code:
```
public class Customer {
private int CustomerId { get; set; }
public string CompanyName { get; set; }
protected string State { get; set; }
public string City { get; set; }
public Customer(int CustomerId, string CompanyName, string State, string City) {
this.CustomerId = CustomerId;
this.CompanyName = CompanyName;
this.State = State;
this.City = City;
}
public Customer() {}
}
public interface ICustomer {
string GetCustomerById(int customerId);
string GetCustomerByDate(DateTime dateFrom, DateTime dateTo);
}
public class MyCustomerClass : Customer, ICustomer {
public string Zip { get; set; }
public string Phone { get; set; }
public string GetCustomerById(int customerId) {
}
public string GetCustomerByDate(DateTime dateFrom, DateTime dateTo) {
}
}
```
For each of the following statements, select Yes if the statement is true. Otherwise, select No.
* All of the objects derived from ``MyCustomerClass`` have ``CustomerId`` as a property.
-> No
* All of the objects derived from ``MyCustomerClass`` have ``CompanyName`` as a property.
-> Yes
* All of the objects derived from ``MyCustomerClass`` have ``CompanyName`` as a property.
-> Yes
———
# ``is`` / ``as``, casting
## ``is`` / ``as``
The ``DoWork()`` method must not throw any exceptions
when converting the obj object to the ``IDataContainer``
interface or when accessing the ``Data`` property.
You need to meet the requirements.
Answer:
```
var dataContainer = obj as IDataContainer;
```
---
## casting
### 1. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-07-31/
You are developing an application by using C#.
The application includes the following code segment.
```
public interface CellTypeDelegate {
string Data { get; set; }
}
void DoWork(object obj) {
if (null != dataContainer) {
Console.WriteLine(dataContainer.Data);
}
}
```
The ``DoWork()`` method must throw an ``InvalidCastException`` exception
if the obj object is not of type ``IDataContainer`` when accessing the ``Data`` property.
You need to meet the requirements.
Which code segment should you insert at line 07?
A.
``var dataContainer = (IDataContainer) obj;``
B.
``var dataContainer = obj as IDataContainer;``
C.
``var dataContainer = obj is IDataContainer;``
D.
``dynamic dataContainer = obj;``
Answer D:
### [Casting and type conversions (C# Programming Guide)](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions)
---
### 2. https://www.briefmenow.org/microsoft/which-code-segment-should-you-replace-line-24-5/
```
public class ItemBase {}
public class Widget : ItemBase {}
class Worker {
void DoWork(object obj) {
Console.WriteLine("In DoWork(object)"");
}
void DoWork(Widget widget) {
Console.WriteLine("In DoWork(Widget)"");
}
void DoWork(ItemBase itemBase) {
Console.WriteLine("In DoWork(ItemBase)"");
}
private void Run() {
object o = new Widget();
DoWork(o);
}
}
```
A. ``DoWork((Widget)o);``
B. ``DoWork(new Widget(o));``
C. ``DoWork(o is Widget);``
D. ``DoWork((ItemBase)o);``
Answer: A
---
##
### 1. https://www.briefmenow.org/microsoft/which-code-should-you-use-to-replace-line-05-9/
You are developing an application.
The application contains the following code segment:
```
ArrayList array1 - new ArrayList();
int var1 = 10;
int var2;
array1.Add(var1);
var2 = array1[0];
```
When you run the code, you receive the following error message:
“Cannot implicitly convert type ``object`` to ``int``.
An explicit conversion exists (are you missing a cast?).”
You need to ensure that the code can be compiled.
Which code should you use to replace line 05?
A. ``var2 = arrayl[0] is int;``
B. ``var2 = ((List<int>)arrayl) [0];``
C. ``var2 = arrayl[0].Equals(typeof(int));``
D. ``var2 = (int) arrayl [0];``
Answer: D
Compiler will raise error for A, B, C, except D.
---
### 2. https://www.briefmenow.org/microsoft/which-code-should-you-use-to-replace-line-05-10/
You are developing an application.
The application contains the following code segment:
```
ArrayList array1 - new ArrayList();
int var1 = 10;
int var2;
array1.Add(var1);
var2 = array1[0];
```
When you run the code, you receive the following error message:
“Cannot implicitly convert type object to int.
An explicit conversion exists (are you missing a cast?).”
You need to ensure that the code can be compiled.
Which code should you use to replace line 05?
A. ``var2 = ((List<int>) array1) [0];``
B. ``var2 = array1[0].Equals(typeof(int));``
C. ``var2 = Convert.ToInt32(array1[0]);``
D. ``var2 = ((int[])array1)[0];``
Answer: C
Compiler will raise error for A, B, D, except C.
___
# Generic
## Generic with type constraint / ``new()``
### 1.
You are creating an application that manages information about ``zoo`` animals.
The application includes a class named ``Animal`` and a method named ``Save``.
The ``Save()`` method must be strongly typed.
It must allow only types inherited from the ``Animal`` class
that uses a constructor that accepts no parameters.
You need to implement the ``Save()`` method.
Answer:
```
public static void Save<T>(T target) where T: Animal, new() {
}
```
---
### 2. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1239/
You are creating an application that manages information about your company’s products.
The application includes a class named ``Product`` and a method named ``Save``.
The ``Save()`` method must be __strongly typed__.
It must __allow only types inherited from the ``Product`` class
that use a constructor that accepts no parameters__.
You need to implement the ``Save()`` method. Which code segment should you use?
A. ``public static void Save(Product target) { ... }``
B. ``public static void Save<T>(T target) where T: new(), Product { ... }``
C. ``public static void Save<T>(T target) where T: Product { ... }``
D. ``public static void Save<T>(T target) where T: Product, new() { ... }``
Answer: D
---
### 3. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1242/
You are creating an application that manages information about your company’s products.
The application includes a class named ``Product`` and a method named ``Save``.
The ``Save()`` method must be strongly typed.
It must allow only types inherited from the ``Product`` class
that use a constructor that accepts no parameters.
You need to implement the ``Save()`` method.
Which code segment should you use?
A. ``public static void Save(Product target) { ... }``
B. ``public static void Save<T>(T target) where T: Product { ... }``
C. ``public static void Save<T>(T target) where T: new()``
D. ``public static void Save<T>(T target) where T: Product, new() { ... }``
Answer: D
---
### 4. https://www.briefmenow.org/microsoft/you-need-to-ensure-that-createobject-compiles-successfully-5/
You are writing the following method:
```
public T CreateObject<T>()
{
T obj = new T();
return obj;
}
```
You need to ensure that ``CreateObject`` compiles successfully.
What should you do?
A.
Insert the following code at line 02:
``where T : new()``
B.
Replace line 01 with the following code:
``public void CreateObject<T>()``
C.
Replace line 01 with the following code:
``public Object CreateObject<T>()``
D.
Insert the following code at line 02:
``where T : Object``
Answer: A
___
# sealed/ class inheritance, interface
## https://www.briefmenow.org/microsoft/which-two-code-segments-can-you-use-to-achieve-this-goal-25/
You are developing an application.
The application includes classes named ``Mammal`` and ``Animal``
and an interface named ``IAnimal``.
The ``Mammal`` class must meet the following requirements:
It must either inherit from the ``Animal`` class or implement the ``IAnimal`` interface.
It must be inheritable by other classes in the application.
You need to ensure that the Mammal class meets the requirements.
Which two code segments can you use to achieve this goal?
```
abstract class Mammal: IAnimal { ... }
abstract class Mammal: Animal { ... }
```
---
## 2
You are developing an application.
The application includes ``classes`` named ``Employee`` and Person
and an ``interface`` named ``IPerson``.
The Employee class must meet the following requirements:
It must either inherit from the ``Person`` class or implement the ``IPerson`` interface.
--> Employee : Persion / Employee : ``IPerson``
It must be inheritable by other classes in the application.
--> inheritable --> 不能有 ``sealed``
You need to ensure that the Employee class meets the requirements.
Which two code segments can you use to achieve this goal? (Each correct answer presents a complete
solution. Choose two.)
BD
---
# modifier ``virtual``/ ``override``/ ``new`` to a method
## 1. https://www.briefmenow.org/microsoft/which-four-lines-of-code-should-you-use-in-sequence-4/
You are developing a C# console application that outputs information to the screen. The following code
segments implement the two classes responsible for making calls to the Console object:
```
abstract class BaseLogger {
public virtual void Log(string message) {
Console.WriteLine("Base: " + message);
}
public void LogCompleted() {
Console.WriteLine("LogCompleted");
}
}
class Logger: BaseLogger {
public override void Log(string message) {
Console.WriteLine(message);
}
public new void LogCompleted() {
Console.WriteLine("Finished");
}
}
```
When the application is run, the console output must be the following text:
```
Log started
Base: Log continuing
Finished
```
You need to ensure that the application outputs the correct text.
Which four lines of code should you use in sequence?
* ``logger.Log("Base: Log continuing");``
* ``((BaseLogger)logger).Log("Log continuing");``
* ``var logger = new BaseLogger();``
* ``((BaseLogger)logger).LogCompleted();``
* ``logger.Log("Log started");``
* ``BaseLogger logger = new Logger();``
* ``logger.LogCompleted();``
Answer:
```
BaseLogger logger = new Logger();
logger.Log("Log started");
logger.Log("Base: Log continuing");
logger.LogCompleted();
```
---
# ExtensionMethods
##
You are developing a class named ``ExtensionMethods``.
You need to ensure that the ``ExtensionMethods`` class
implements the ``IsEmail()`` method on ``string`` objects.
Answer:
```
public static class ExtensionMethods {
public static bool IsUrl(this string str) {
var regex = new Regex(...)
return regex.IsMatch(str);
}
}
```
---
## https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-307/
You are developing a class named ``ExtensionMethods``.
You need to ensure that the ``ExtensionMethods`` class
implements the ``IsEmail()`` extension method on ``string`` objects.
How should you complete the relevant code?
```
{
public static bool IsEmail(
) {
var regex = new Regex(...)
return regex.IsMatch(str);
}
}
```
* ``public static class ExtensionMethods``
* ``public class ExtensionMethods``
* ``this String str``
* ``String str``
* ``public static class ExtensionMethods``
____
# Boxing / Unboxing
##
You are implementing a method named ``Calculate`` that
performs conversions between value types and reference types.
The following code segment implements the method.
```
public static void Calculate(float amount) {
object amountRef = amout;
Console.WriteLine(blance)
}
```
You need to ensure that the application __does not throw exceptions__ on invalid conversions.
```
int balance = (int) (float) amountRef
```
---
### 2. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-04-79/
You are implementing a method named ``FloorTemperature`` that
performs conversions between value types and reference types.
The following code segment implements the method.
```
public static void FloorTemperature(float degrees) {
object degreesRef = degrees;
Console.WriteLine(result)
}
```
You need to ensure that the application __does not throw exceptions__ on invalid conversions.
Which code segment should you insert at line 04?
A. ``int result = (int)degreesRef;``
B. ``int result = (int)(double)degreesRef;``
C. ``int result = degreesRef;``
D. ``int result = (int)(float)degreesRef;``
Answer: D
---
# Exception Handling
## class inheritance & define customized exception
### 1. https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-304/
You are developing an application that implements a set of custom exception types.
You declare the __custom exception types__ by using the following code segments:
```
public class AdvenureWorksException: System.Exception {}
public class AdvenureWorksDbException: AdvenureWorksException {}
public class AdvenureWorksValidationException: AdvenureWorksException {}
```
The application includes a function named ``DoWork`` that
throws .NET Framework exceptions and custom exceptions.
The application contains only the following logging methods:
```
static void Log(Exception ex) { ... }
static void Log(AdvenureWorksException ex) { ... }
static void Log(AdvenureWorksValidationException ex) { ... }
```
The application must meet the following requirements:
When ``AdventureWorksValidationException`` exceptions are caught,
log the information by using the static void Log (AdventureWorksValidationException ex) method.
When ``AdventureWorksDbException`` or other ``AdventureWorksException`` exceptions are caught,
log the information by using the ``static void Loq(AdventureWorksException ex)`` method.
You need to meet the requirements.
```
try {
DoWork();
}
catch (AdventureWorksValidationException ex) {
Log(ex); // AdvenureWorksValidationException
}
catch (AdventureWorksException ex) {
Log(ex); // AdventureWorksException
}
catch (Exception ex) {
Log(ex); // Exception
}
```
### Exception Handling - 先抓 subclass / Derived class
---
### 2. https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-309/
You are developing an application that implements a set of custom exception types.
You declare the __custom exception types__ by using the following code segments:
```
public class ContosoException: System.Exception {}
public class ContosoDbException: ContosoException {}
public class ContosoValidationException: ContosoException {}
```
The application includes a function named ``DoWork`` that
throws .NET Framework exceptions and custom exceptions.
The application contains only the following logging methods:
```
static void Log(Exception ex) { ... }
static void Log(ContosoException ex) { ... }
static void Log(ContosoValidationException ex) { ... }
```
The application must meet the following requirements:
When ``ContosoValidationException`` exceptions are caught,
log the information by using the static void Log (ContosoValidationException ex) method.
When ``ContosoDbException`` or other ``ContosoException`` exceptions are caught,
log the information by using the ``static void Loq(ContosoException ex)`` method.
You need to meet the requirements.
* ``(ContosoValidationException ex)``
* ``(ContosoException ex)``
* ``(Exception ex)``
* ``(ContosoDbException ex)``
Answer:
```
try {
DoWork();
}
catch (ContosoValidationException ex) {
Log(ex); // AdvenureWorksValidationException
}
catch (ContosoException ex) {
Log(ex); // AdventureWorksException
}
catch (Exception ex) {
Log(ex); // Exception
}
```
---
## concept of throw
### 1.
You are developing an application that uses __structured exception handling__.
The application includes a class named ``ExceptionLogger``.
The ``ExceptionLogger`` class implements a method named ``LogException``
by using the following code segment:
```
public static void LogException(Exception ex)
```
You have the following requirements:
Log all exceptions by using the ``LogException()`` method of the ``ExceptionLogger`` class.
Rethrow the original exception, including the entire exception stack.
You need to meet the requirements.
Which code segment should you use?
```
catch (Exception ex) {
ExceptionLogger.LogException(ex);
throw;
}
```
### [CA2200: Rethrow to preserve stack details](http://msdn.microsoft.com/en-us/library/ms182363(v=vs.110).aspx):
Once an exception is thrown,
part of the information it carries is the stack trace.
The stack trace is a list of the method call hierarchy that
starts with the method that throws the exception and
ends with the method that catches the exception.
If an exception is re-thrown by specifying the exception
in the throw statement, the stack trace is restarted
at the current method and the list of method calls
between the original method that threw the exception and
the current method is lost.
To keep the original stack trace information with the exception,
use the throw statement without specifying the exception.
---
### 2. https://www.briefmenow.org/microsoft/how-should-you-write-the-catch-block-4/
You are creating a method that saves information to a database.
You have a static class named ``LogHelper``.
``LogHelper`` has a method named Log to log the exception.
You need to use the ``LogHelper.Log`` method to log the exception
raised by the database server.
The solution must ensure that the exception can be caught by the calling method,
while preserving the original stack trace.
How should you write the catch block?
* ``catch {``
* ``catch (SqlException ex) {``
* ``catch (FileNotFoundException ex) {``
* ``throw;``
* ``}``
* ``throw new FileNotFoundException();``
* ``throw ex;``
* ``LogHelper.Log(ex);``
* ``throw new SqlException();``
Answer:
```
catch (SqlException ex) {
LogHelper.Log(ex);
throw;
}
```
---
### 3. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1241/
You are developing an application that uses structured exception handling.
The application includes a class named ``Logger``.
The ``Logger`` class implements a method named ``Log``
by using the following code segment:
```
public static void Log(Exception ex) { }
```
You have the following requirements:
Log all exceptions by using the ``Log()`` method of the ``Logger`` class.
Rethrow the original exception, including the entire exception stack.
You need to meet the requirements. Which code segment should you use?
A.
```
catch {
var ex = new Exception();
throw ex;
}
```
B.
```
catch (Exception ex) {
Logger.Log(ex);
throw ex;
}
```
C.
```
catch (Exception ex) {
Logger.Log(new Exception());
throw;
}
```
D.
```
catch (Exception ex) {
Logger.Log(ex);
throw;
}
```
Answer: D
---
## Overflow exception
### 1. https://www.briefmenow.org/microsoft/which-type-of-block-should-you-use-5/
You are developing code for a class named ``Account``.
The ``Account`` class includes the following method:
```
public void Deposit(int dollars, int cents) {
int totalCents = cents + this.cents;
int extraDollars = totalCents / 100;
this.cents = totalCents - 100 * extraCents;
this.dollars += dollars + extraDollars;
}
```
You need to ensure that
__overflow exceptions are thrown when there is an error__.
Which type of block should you use?
A. ``checked``
B. ``try``
C. ``using``
D. ``unchecked``
---
## AppDomain.UnhandledException
### https://www.briefmenow.org/microsoft/which-two-actions-should-you-perform-1395/
An application is throwing unhandled ``NullReferenceException``
and ``FormatException`` errors. The stack trace shows that
the exceptions occur in the ``GetWebResult()`` method.
The application includes the following code to parse XML data retrieved from a web service.
```
int GetWebResult(XElement result) {
return int.Parse(result.Element("response").Value);
}
```
You need to handle the exceptions __without interfering with
the existing error-handling infrastructure__.
Which two actions should you perform?
A. Replace line 03 with the following code segment:
```
int returnValue;
int.Parse(result.Element("response").Value, out returnValue);
return returnValue;
```
B. Replace line 03 with the following code segment:
```
return int.ParseOptions.Safe(result.Element("response").Value);
```
C. Register an event handler with ``AppDomain.CurrentDomain.UnhandledException``.
D. Use a ``try...catch`` statement to handle the exception in the ``GetWebResult()`` method
Answer: A, C
---
A:
The ``TryParse`` method is like the Parse method,
except the ``TryParse`` method does not throw an exception if the conversion fails.
It eliminates the need to use exception handling
to test for a FormatException in the event that
s is invalid and cannot be successfully parsed.
C: ``UnhandledException`` event handler
If the ``UnhandledException`` event is handled in the default application domain,
it is raised there for any unhandled exception in any thread,
no matter what application domain the thread started in.
If the thread started in an application domain that
has an event handler for UnhandledException,
the event is raised in that application domain.
---
### [ParseOptions](https://docs.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.parseoptions?view=roslyn-dotnet)
``ParseOptions`` 沒有 ``Safe()`` method
---
### [AppDomain.UnhandledException Event](https://docs.microsoft.com/en-us/dotnet/api/system.appdomain.unhandledexception?view=netcore-3.1)
* Occurs when an exception is not caught.
這是一個 event delegate
```
public event UnhandledExceptionEventHandler UnhandledException;
```
#### Examples
The following example demonstrates the ``UnhandledException`` event.
It defines an event handler, ``MyHandler``,
that is invoked whenever an unhandled exception is thrown
in the default application domain. It then throws two exceptions.
The first is handled by a ``try/catch`` block.
The second is unhandled and invokes the ``MyHandle`` routine
before the application terminates.
```
using System;
using System.Security.Permissions;
public class Example {
[SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
public static void Main() {
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
try {
throw new Exception("1");
} catch (Exception e) {
Console.WriteLine("Catch clause caught : {0} \n", e.Message);
}
throw new Exception("2");
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
}
}
// The example displays the following output:
// Catch clause caught : 1
//
// MyHandler caught : 2
// Runtime terminating: True
//
// Unhandled Exception: System.Exception: 2
// at Example.Main()
```
---