---
# System prepended metadata

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

---

# C# Exam Questions 70-483 Reading - Syntax - Part 2

###### 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 1](https://hackmd.io/@sfRJH1u7S464tSaizL7ZsQ/SkBK5tB2P)

---

# Singleton / Thread Safe

## Thread Safety Singleton using Double Check Locking

### 1. 

You are developing an application that includes a class named ``Kiosk``. 
The ``Kiosk`` class includes a ``static`` property named ``Catalog``. 
The ``Kiosk`` class is defined by the following code segment. 

```
public class Kiosk {
    static Catalog _catalog = null;
    static object _lock = new object;

    public static Catalog Catalog {
        get { 
            //
            if (null == _catalog) {
                lock (_lock) {
                    if (null == _catalog) {
                        _catalog = new Catalog();
                    }
                }
            }
            //
            return _catalog; 
        }
    }
}
```

You have the following requirements:
Initialize the _catalog field to a Catalog instance.
Initialize the _catalog field only once.
Ensure that the application code acquires a lock 
only when the _catalog object must be instantiated.
You need to meet the requirements.
Which three code segments should you insert in sequence at line 09?

---

### 2. https://www.briefmenow.org/microsoft/which-three-code-segments-should-you-insert-in-sequence-2/

You are developing an application that includes a class named ``Warehouse``. 
The ``Warehouse`` class includes a ``static`` property named ``Inventory``. 
The ``Warehouse`` class is defined by the following code segment. 

```
public class Warehouse {
    static Inventory _inventory = null;
    static object _lock = new object;

    public static Inventory Inventory {
        get { 
            //
            if (null == _inventory) {
                lock (_lock) {
                    if (null == _inventory) {
                        _inventory = new Inventory();
                    }
                }
            }
            //
            return _inventory; 
        }
    }
}
```

You have the following requirements:
Initialize the ``_inventory`` field to an ``Inventory`` instance.
Initialize the ``_inventory`` field only once.
Ensure that the application code acquires a ``lock`` 
only when the ``_inventory`` object must be instantiated.
You need to meet the requirements.
Which three code segments should you insert in sequence at line 09? 

----

## Thread-Safe

### 1. 

You are adding a ``public`` method named ``UpdateScore`` 
to a ``public`` class named ``ScoreCard``.
The code region that updates the score field 
must meet the following requirements:
It must be __accessed by only one thread at a time__.
It must __not be vulnerable to a deadlock situation__.
You need to implement the ``UpdateScore()`` method.

Add a ``private`` object named ``lockObject`` to the ``ScoreCard`` class.
Place the code region inside the following ``lock`` statment:

```
lock (lockObject) {
   ...
}
```

該 class 不論被建立多少次，static member 只會有一份在記憶體中
通常用來定義常數 - 它還可在外部來初始化!!

---

### 2. https://www.briefmenow.org/microsoft/you-need-to-implement-the-updategrade-method-6/

You are adding a ``public`` method named ``UpdateGrade`` to a ``public`` class named ``ReportCard``.
The code region that updates the ``grade`` field must meet the following requirements:
It must be accessed by only one thread at a time.
It must not be vulnerable to a deadlock situation.
You need to implement the ``UpdateGrade()`` method.
What should you do?


A.
Add a private object named ``lockObject`` to the ``ReportCard`` class.
Place the code region inside the following lock statment:
lock (lockObject) { ... }

B.
Place the code region inside the following lock statement:
lock(this) { ... }

C.
Add a public object named ``lockObject`` to the ``ReportCard`` class.
Place the code region inside the following lock statment:
lock (typeof(ReportCard)) { ... }

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

---

Answer: A


### [MethodImplOptions.Synchronized vs. lock](https://social.msdn.microsoft.com/Forums/vstudio/en-US/b6a72e00-d4cc-4f29-a6a0-b27551f78b9b/methodimploptionssynchronized-vs-lock?forum=csharpgeneral)

```
[MethodImpl(MethodImplOptions.Synchronized)]  
public static void DoSomething(object targetobject) {   
	// do some init work  
	// do something on targetobject  
} 
```

Now I read that the following code does exactly the same... 
I thought this is not applicable because the second thread could change the parameter:
```
// object1.DoSomething(obejct1) //--> targetobject is object1
// object2.DoSomething(obejct2) //--> targetobject is object2
// DoSomething on object1 gets lock 
// DoSomething does its work on object2 instead of object1!!
```

```
public static void DoSomething(object targetobject) {  
 	// do some init work  
 	lock(this) {   
  		// do something on targetobject  
	}  
} 
```

---

# Interface - difference between implicitly implementation and explicit implementation

## 1. https://www.briefmenow.org/microsoft/which-signature-should-you-use-for-each-method-4/

You are developing the following classes named:
``Class1``
``Class2``
``Class3``

All of the classes will be part of a single assembly named ``Assembly.dll``. 
``Assembly.dll`` will be used by multiple applications.
All of the classes will implement the following interface, 
which is also part of ``Assembly.dll``:

```
public interface Interface1 {
	void Method1(decimal amount);
	void Method2(decimal amount);
}
```

You need to ensure that the ``Method2`` method for the ``Class3`` class 
can be executed only when instances of the class 
are accessed through the Interface1 interface. 
The solution must ensure that calls to the ``Method1`` method
can be made either through the interface or through an instance of the class.
Which signature should you use for each method? 

``Method1``:
* ``internal void Method1(decimal amount)``
* ``private void Method1(decimal amount)``
* ``public void Method1(decimal amount)``
* ``void Interface1.Method1(decimal amount)``

``Method2``:
* ``internal void Method2(decimal amount)``
* ``private void Method2(decimal amount)``
* ``public void Method2(decimal amount)``
* ``void Interface1.Method2(decimal amount)``

Answer:

```
public void Method1(decimal amount)
void Interface1.Method2(decimal amount)
```

---

# delegate

## using delegate via Anonymous Method

### 1. 

You are developing an application that includes a class named ``UserTracker``. 
The application includes the following code segment. 

```
public delegate void AddUserCallback(int i);

public class UserTracker {
    List<User> users = new List<User>();

    public void AddUser(string name, AddUserCallback callback) {
        users.Add(new User(name));
        callback((user.Count));
    }
}

public class Runner {
    UserTracker tracker = new UserTracker();

    public void Add(string name) {
        tracker.AddUser(name, delegate(int i)) {
            ....
        });
    }
}
```

You need to add a user to the ``UserTracker`` instance.

Answer: Option D

---

### 2. https://www.briefmenow.org/microsoft/you-need-to-add-a-user-to-the-booktracker-instance-4/ 

You are developing an application that includes a class named ``BookTracker`` 
for tracking library books. The application includes the following code segment. 

```
public delegate void AddBookCallback(int i);

public class BookTracker {
    List<Book> books = new List<Book>();

    public void AddBook(string name, AddBookCallback callback) {
        books.Add(new Book(name));
        callback((books.Count));
    }
}

public class Runner {
    BookTracker tracker = new BookTracker();

    public void Add(string name) {
        tracker.AddBook(name, delegate(int i)) {
            ....
        });
    }
}
```

You need to add a user to the ``BookTracker`` instance. What should you do?

A. 
Insert the following code segment at line 14:
```
private static void PrintBookCount(int i) {
	...
}
```
Insert the following code segment at line 18:
```
AddBookCallback delegate = PrintBookCount;
```

B.
Insert the following code segment at line 18:
```
tracker.AddBook(name, delegate(int i)) {
	....
});
```

C. 
Insert the following code segment at line 11:
```
delegate void AddBookDelegate(BookTracker bookTracker);
```
Insert the following code segment at line 18:
```
AddBookDelegate addDelegate = (bookTracker) => {
	...
}
addDelegate(bookTracker);
```

D. 
Insert the following code segment at line 11:
```
delegate void AddBookDelegate(string name, AddBookCallback callback);
```
Insert the following code segment at line 18:
```
AddBookDelegate addr = (i, callback) => {
	...
}
```


Answer: Option B

---

### 3. https://www.briefmenow.org/microsoft/you-need-to-add-a-book-to-the-booktracker-instance-5/

You are developing an application that includes a class named ``BookTracker`` 
for tracking library books. 
The application includes the following code segment.

```
public delegate void AddBookCallback(int i);

public class BookTracker {
    List<Book> books = new List<Book>();

    public void AddBook(string name, AddBookCallback callback) {
        books.Add(new Book(name));
        callback((books.Count));
    }
}

public class Runner {
    BookTracker tracker = new BookTracker();

    public void Add(string name) {
        tracker.AddBook(name, delegate(int i)) {
            ....
        });
    }
}
```

You need to add a ``book`` to the ``BookTracker`` instance.
What should you do?

A. 
Insert the following code segment at line 18:
```
tracker.AddBook(name, delegate(int i)) {
	....
});
```

B. 
Insert the following code segment at line 11:
```
delegate void AddBookDelegate(string name, AddBookCallback callback);
```
Insert the following code segment at line 18:
```
AddBookDelegate addr = (i, callback) => {
	...
}
```

C. 
Insert the following code segment at line 11:
```
delegate void AddBookDelegate(BookTracker bookTracker);
```
Insert the following code segment at line 18:
```
AddBookDelegate addDelegate = (bookTracker) => {
	...
}
addDelegate(bookTracker);
```

D. Insert the following code segment at line 14:
```
private static void PrintBookCount(int i) {
	...
}
```
Insert the following code segment at line 18:
```
AddBookCallback delegate = PrintBookCount;
```
---

Answer: A

```
AddBookCallback delegate = PrintBookCount;
or 
AddBookCallback delegate = (int i) => { ... }; // lambda expression
or 
AddBookCallback delegate = delegate(int i) { ... }; // anonymous method
```

---

### 4. https://www.briefmenow.org/microsoft/how-should-you-rewrite-lines-03-through-06-of-the-method-5/

You have a ``List`` object that is generated by executing the following code:

```
List<string> departments = new List<string>() {
    "Accounting", "Marketing", "Sales", "Manufacturing", "Information Systems", "Training"
};
```

You have a method that contains the following code:

```
private bool GetMatches(List<string> departments, string searchTerm) {
    var findDepartment = departments.Exists((delegate(string deptName) {
        return deptName.Equal(searchTerm);
    }
    ));
    return findDepartment;
}
```
You need to alter the method to use a lambda statement.
How should you rewrite lines 03 through 06 of the method?

A. ``var findDepartment = departments.First(x => x == searchTerm);``

B. ``var findDepartment = departments.Where(x => x == searchTerm);``

C. ``var findDepartment = departments.Exists(x => x.Equals(searchTerm));``

D. ``var findDepartment = departments.Where(x => x.Equals(searchTerm));``

Answer: C


```
delegate(string deptName) {
	return deptName.Equal(searchTerm);
}
```

->

```
(string deptName) => { return deptName.Equal(searchTerm); };
//or
deptName => deptName.Equal(searchTerm);
```

---

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

You are developing an application for a bank. 
The application includes a method named ``ProcessLoan`` that processes loan applications. 
The ``ProcessLoan()`` method uses a method named ``CalculateInterest``. 
The application includes the following code:

```
static decimal CalculateInterest(decimal amount, decimal rate, int term) {
	return amount * rate * term;
}
static decimal ProcessLoan() {
	CalculateLoanInterest loanInterestProcess = CalculateInterest
	return loanInterestProcess(4500m, 0.065m, 4);
}
```

You need to declare a delegate to support the ``ProcessLoan()`` method.
Which code segment should you use?


A. ``public delegate decimal LoanProcessor(decimal loanAmount, decimal loanRate, int term);``

B. ``public delegate int LoanProcessor(decimal loanAmount, decimal loanRate, int term);``

C. ``public delegate decimal CalculateLoanInterest(decimal loanAmount, decimal loanRate, int term);``

D. ``public delegate decimal ProcessLoad();``

Answer: C

---

## event, delegate involvement

### 1.

You are modifying an application that processes leases. 
The following code defines the Lease class. 

```
public class Lease {
    public event MaximumTermReachedHandler OnMaximumTermReached;
    private int _term;
    private const int MaximumTerm = 5;
    private const decimal Rate = 0.034m;
    public int Term {
        get { return _term; }
        set {
            if (value <= MaximumTerm) {
                _term = value;
            } else {
                if (null != OnMaximumTermReached) {
                    OnMaximumTermReached(this, new EventArgs());
                }
            }
        }
    }
}

public delegate void MaximumTermReachedHandler(object source, EventArgs e);
```

``Leases`` are restricted to a maximum term of 5 years. 
The application must send a notification message if a lease request exceeds 5 years.
You need to implement the notification mechanism.
Which two actions should you perform? 

---

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

You are modifying an application that processes loans. 
The following code defines the ``Loan`` class. 

```
public class Loan {
	[]
	private int _term;
	private const int MaximumTerm = 10;
	private const decimal Rate = 0.034m;
	private int Term {
		get { return _term; }
		set {
      		if (value <= MaximumTerm) { _term = value; }
      		else {
      			[]
      		}
		}
	}
}
public delegate void MaximumTermReachedHandler(object source, EventArgs, e);
```

Loans are restricted to a maximum term of 10 years. 
The application must send a notification message if a loan request exceeds 10 years.
You need to implement the notification mechanism.
Which two actions should you perform?

A. Insert the following code segment at line 03:
``public string MaximumTermReachedEvent { get; set; }``

B. Insert the following code segment at line 21:
```
if (null != OnMaximumTermReached) {
	OnMaximumTermReached(this, new EventArgs());
}
```

C. Insert the following code segment at line 03:
``private string MaximumTermReachedEvent;``

D. Insert the following code segment at line 03:
``public event MaximumTermReachedHandler OnMaximumTermReached;``

E. Insert the following code segment at line 21:
``value = MaximumTerm``

F. Insert the following code segment at line 21:
``value = 9``

Answer: B, D


---

## event delegate ``EventHandler``

### 1. with lambda expression

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

You are implementing a method that creates an instance of a class named ``User``. 
The ``User`` class contains a public event named ``Renamed``. 
The following code segment defines the ``Renamed`` event:

```
Public event EventHandler<RenameEventArgs> Renamed;
```

You need to create an __event handler__ for the ``Renamed`` event 
by using a lambda expression.
How should you complete the relevant code? 

* ``user.Renamed -= delegate(object sender, RenameEventArgs e)``
* ``user.Renamed -= (sender, e) =>``
* ``user.Renamed += delegate(object sender, RenameEventArgs e)``
* ``user.Renamed += (sender, e) =>``
* ``users[0] = user;``  // array
* ``users.Add(user);``
* ``users.Insert(user);``

Answer: 

```
List<User> users = new List<User>();

public void AddUser(string name) {
    User user = new User(name);
    user.Renamed += (sender, e) =>
    {
        Log("User {0 was renamed to {1}", e.oldName, e.Name);
    };    
    users.Add(user);
}
```

``+=`` operator to register an event

```
//register an event via lambda expression
user.Renamed += (sender, e) => { ... };

//register an event via Anonymous method
delegate(object sender, RenameEventArgs e) { ... };
```

---

### 2. Multicast

https://www.briefmenow.org/microsoft/hot-area-86/

You have the following code:

```
public class Alert {
	public event EventHandler<EventArgs> SendMessage;

	public void Exceute() {
		SendMessage(this, new EventArgs());
	}
}


public class Subscriber {
	Alert alert = new Alert();

	public void Subscribe() {
		alert.SendMessage += (sender, e) => { Console.WriteLine("First"); };
		alert.SendMessage += (sender, e) => { Console.WriteLine("Second"); };
		alert.SendMessage += (sender, e) => { Console.WriteLine("Third"); };
		alert.SendMessage += (sender, e) => { Console.WriteLine("Third");};
	}

	public void Exceute() {
		alert.Exceute();
	}

	public static void Main() {
		Subscriber subscriber = new Subscriber();
		subscriber.Subscribe();
		Subscribe.Exceute();
	}	
}
```

For each of the following statements, 
select Yes if the statement is true. Otherwise, select No.

If there are no subscribers to the ``SendMessage`` event the ``Exceute`` method on the ``Alert`` class will throw an exception
-> Yes
```
Exception thrown: 'System.NullReferenceException' in HelloDotnet.dll
error: Object reference not set to an instance of an object.
```
When the application runs, ``First`` will alway appear before ``Second``.
-> Yes
When the application runs, ``Third`` will be displayed once.
-> No


---

## Difference between ``Action`` and ``Func``

### 1. https://www.briefmenow.org/microsoft/which-type-of-delegate-should-you-use-5/

You are developing an application.
You need to declare a delegate for a method that 
__accepts an integer__ as a parameter, and then __returns an integer__.
Which type of delegate should you use?

A. ``Action<int>``

B. ``Action<int, int>``

C. ``Func<int, int>``

D. ``Func<int>``

Answer: C

---

# Unclassified

## 1

The application must meet the following requirements:
Return only orders that have an ``OrderDate`` value other than null.
Return only orders that were placed in the year specified 
in the OrderDate property or in a later year.

A.
Where order.OrderDate.Value != null && order.OrderDate.Value.Year > = year

---

## 2. https://www.briefmenow.org/microsoft/which-form-should-you-implement-the-score-member-5/

You are creating a class named ``Game``. 
The ``Game`` class must meet the following requirements:
Include a member that represents the __score__ for a ``Game`` instance.
__Allow external code to assign a value to the score member__.
__Restrict the range of values that can be assigned to the score member__.
You need to implement the score member to meet the requirements.
In which form should you implement the score member?

A. ``protected field``

B. ``public static field``

C. ``public static property``

D. ``public property``

Answer: D

e.g.,

```
public class IeGameModel {

	public IeGameModel() { this.score = 0; }

	public int score { 
		get { return score; }
		set {
			if ( (value >= 0) && (value <= 100) ) {
				score = value;
			}
			else {
				Console.WriteLine("value {0} is out of range < 0 or > 100!!", value);
				score = 0;
			}
		} 
	}	
}
```

---

## 3. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-03-57/

You are developing an application that uses several objects. 
The application includes the following code segment.

```
private bool IsNull(object obj) {
    []
    return false;
}
```

You need to evaluate whether an object is null.
Which code segment should you insert at line 03?

A. ``if (null = object) { return true; }``
B. ``if (null) { return true; }`` 
C. ``if (null == 0) { return true; }`` 
D. ``if (null == object) { return true; }`` 

Answer: D

---

## 4. Method overloading

### 4.1. https://www.briefmenow.org/microsoft/you-need-to-create-a-method-that-can-be-called-by-using-3/

You need to create a method that can be called by __using a varying number of parameters__.
What should you use?

A. Method overloading

B. Interface

C. Named parameters

D. Lambda expressions

Answer: A

Member overloading means creating two or more members on the same type that differ only in the number or type of parameters but have the same name.
Overloading is one of the most important techniques for improving usability, productivity, and readability of reusable libraries. Overloading on the number of parameters makes it possible to provide simpler versions of constructors and methods. Overloading on the parameter type makes it possible to use the same member name for members performing identical operations on a selected set of different types.

e.g., 

```
public void DoWork() {
	
}

public void DoWork(string name) {
	
}

public void DoWork(string name, string address) {
	
}
```

---

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


You are modifying an existing banking application.
The application includes an ``Account`` class and a ``Customer`` class. 
The following code segment defines the classes.

```
class Account {
	public Account(decimal balance, int term, decimal rate) {
		this.Balance = balance;	
		this.Term = term;
		this.Rate = rate;
	}
	public decimal Balance { get; set; }
	public decimal Rate { get; set; }
	public int Term { get; set; }
}

class Customer {
	public Customer(string firstName, string lastName, Collection<Account> accounts) {
		this.FirstName = firstName;	
		this.LastName = lastName;
		this.AccountCollection = accounts;
	}
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public Collection<Account> AccountCollection { get; set; }
}
```

You populate a collection named ``customerCollection`` 
with ``Customer`` and ``Account`` objects by using the following code segment:

```
Collection<Customer> customerCollection = new Collection<Customer>();
Collection<Account> customerAccounts = new Collection<Account>();
customerAccounts.Add(new Account(1000m, 2, 0.025m));
customerAccounts.Add(new Account(3000m, 4, 0.045m));
customerAccounts.Add(new Account(5000m, 6, 0.045m));
customerCollection.Add(new Customer("David" "Jones", customerAccounts));
```

You create a ``largeCustomerAccounts`` collection to store the ``Account`` objects 
by using the following code segment:
```
Collection<Account> largeCustomerAccounts = new Collection<Account>();
```
All accounts with a ``Balance`` value greater than or equal to 1,000,000 must be tracked.
You need to populate the ``largeCustomerAccounts`` collection with ``Account`` objects.
Which code segment should you use?

A.
```
foreach(Customer customer in customerCollection) {
	foreach(Account account in largeCustomerAccounts) {
		if(account.Balance >= 1000000m) {
			customer.AccountCollection.Add(account);
		}
	}
}
```

B.
```
foreach(Customer customer in customerCollection) {
	foreach(Account account in largeCustomerAccounts) {
		if(account.Balance >= 1000000m) {
			largeCustomerAccounts.Add(account);
		}
	}
}
```

C.
```
foreach(Customer customer in customerCollection) {
	foreach(Account account in customer.AccountCollection) {
		if(account.Balance >= 1000000m) {
			largeCustomerAccounts.Add(account);
		}
	}
}
```

D.
```
foreach(Account account in largeCustomerAccounts) {
	foreach(Customer customer in customerCollection) {
		if(account.Balance >= 1000000m) {
			customer.AccountCollection.Add(account);
		}
	}
}
```

Answer: D

---

### 6. https://www.briefmenow.org/microsoft/you-need-to-adjust-the-loanrate-value-to-meet-the-requi-2/

You are evaluating a method that calculates loan interest.
The application includes the following code segment.

```
private static decimal CalculateInterest(decimal loanAmount, int loanTerm) {
	decimal interestAmount;
	decimal loanRate;
	if (loanTerm > 0 && loanTerm < 5 && loanAmount < 5000m) { loanRate = 0.045m; }
	else if (loanTerm > 5 && loanAmount > 5000m) { loanRate = 0.085m; }
	else { loanRate = 0.055m; }
	interestAmount = loanAmount * loanRate * loanTerm;
	return interestAmount;
}
```

When the ``loanTerm`` value is 3 and the ``loanAmount`` value is 9750, 
the ``loanRate`` must be set to 8.25 percent.
You need to adjust the ``loanRate`` value to meet the requirements.
What should you do?

A. Replace line 04 with the following code segment:
``decimal loanRate = 0.0325m;``

B. Replace line 17 with the following code segment:
``interestAmount = loanAmount * 0.0825m * loanTerm;``

C. Replace line 15 with the following code segment:
``loanRate = 0.0825m;``

D. Replace line 07 with the following code segment:
``loanRate = 0.0825m;``


Answer: C

return the default value as ``0.0825m``


---

