MCSD Certification Toolkit (Exam 70-483): Programming in C# (2013)

Appendix

Answers to Sample Test Questions

Chapter 1: Introducing the Programming in C# Certification

Chapter 1 has no chapter test questions.

Chapter 2: Basic Program Structure

1. You want to declare an integer variable called myVar and assign it the value 0. How can you accomplish this?

b. myVar = 0;

2. You need to make a logical comparison where two values must return true in order for your code to execute the correct statement. Which logical operator enables you to achieve this?

d. &&

3. What kind of result is returned in the condition portion of an if statement?

a. Boolean

4. What are the keywords supported in an if statement?

b. if, else, else if

5. In the following code sample, will the second if structure be evaluated?

bool condition = true;

if(condition)

   if(5 < 10)

       Console.WriteLine("5 is less than 10);

a. Yes

6. If you want to iterate over the values in an array of integers called arrNumbers to perform an action on them, which loop statement enables you to do this?

a. foreach (int number in arrNumbers){}

7. What is the purpose of break; in a switch statement?

b. It causes the code to exit the switch statement.

8. What are the four basic repetition structures in C#?

c. for, foreach, while, do-while

9. How many times will this loop execute?

int value = 0;

do

{

   Console.WriteLine (value);

} while value > 10;

b. 1 time

Chapter 3: Working with the Type System

1. What is the maximum value you can store in an int data type?

d. 4,294,967,296

2. True or false: Double and float data types can store values with decimals.

a. True

3. Which declaration can assign the default value to an int type?

b. int myInt = new int();

4. True or false: structs can contain methods.

a. True

5. What is the correct way to access the firstName property of a struct named Student?

a. string name = Student.firstName;

6. In the following enumeration, what will be the underlying value of Wed?

enum Days {Mon = 1, Tue, Wed, Thur, Fri, Sat, Sun};

b. 3

7. What are two methods with the same name but with different parameters?

a. Overloading

8. What is the parameter in this method known as?

public void displayAbsoluteValue(int value = 1)

b. Optional

9. When you create an abstract method, how do you use that method in a derived class?

b. You must override the method in your derived class.

10. How do you enforce encapsulation on the data members of your class?

a. Create private data members.

c. Use public properties.

11. Boxing refers to:

b. Converting a value type to a reference type

12. What is one advantage of using named parameters?

a. You can pass the arguments in to the method in any order using the parameter names.

13. What is an advantage of using Generics in .NET?

b. Generics enable you to create classes that accept the type at creation time.

14. What does the <T> designator indicate in a generic class?

c. It is a placeholder that will contain the object type used.

15. How are the values passed in generic methods?

b. They are passed by reference.

Chapter 4: Using Types

1. To parse a string that might contain a currency value such as $1,234.56, you should pass the Parse or TryParse method which of the following values?

c. NumberStyles.Currency

2. Which of the following statements is true for widening conversions?

d. All of the above.

3. Which of the following statements is true for narrowing conversions?

b. The source and destination types must be compatible.

4. Assuming total is a decimal variable holding the value 1234.56, which of the following statements displays total with the currency format $1,234.56?

c. Console.WriteLine(total.ToString("c"));

5. Which of the following statements generates a string containing the text "Veni, vidi, vici "?

c. String.Format("{2}, {0}, {3}", "vidi", "Venti", "Veni", "vici")

6. If i is an int and l is a long, which of the following statements is true?

a. i = (int)l is a narrowing conversion.

7. Which of the following methods is the best way to store an integer value typed by the user in a variable?

d. TryParse

8. The statement object obj = 72 is an example of which of the following?

c. Boxing

9. If Employee inherits from Person and Manager inherits from Employee, which of the following statements is valid?

a. Person alice = new Employee();

10. Which of the following is not a String method?

c. StopsWith

11. Which of the following techniques does not create a String containing 10 spaces?

d. Use the String class's Space method passing it 10 as the number of spaces the string should contain.

12. Which of the following statements can you use to catch integer overflow and underflow errors?

a. checked

13. Which of the following techniques should you use to watch for floating point operations that cause overflow or underflow?

c. Check the result for the value Infinity or NegativeInfinity.

Chapter 5: Creating and Implementing Class Hierarchies

1. Which the following statements about the base keyword is false?

c. The base keyword lets a constructor invoke a different constructor in the same class.

2. Which the following statements about the this keyword is false?

b. A constructor can use a this statement and a base statement if the base statement comes first.

3. Suppose you have defined the House and Boat classes and you want to make a HouseBoat class that inherits from both House and Boat. Which of the following approaches would not work?

a. Make HouseBoat inherit from both House and Boat.

4. Suppose the HouseBoat class implements the IHouse interface implicitly and the IBoat interface explicitly. Which of the following statements is false?

b. The code can use a HouseBoat object to access its IBoat members.

5. Which of the following is not a good use of interfaces?

d. To reuse the code defined by the interface.

6. Suppose you want to make a Recipe class to store cooking recipes and you want to sort the Recipes by the MainIngredient property. In that case, which of the following interfaces would probably be most useful?

b. IComparable

7. Suppose you want to sort the Recipe class in question 6 by any of the properties MainIngredient, TotalTime, or CostPerPerson. In that case, which of the following interfaces would probably be most useful?

c. IComparer

8. Which of the following statements is true?

c. A class can inherit from at most one class and implement any number of interfaces.

9. A program can use the IEnumerable and IEnumerator interfaces to do which of the following?

a. Use MoveNext and Reset to move through a list of objects.

10. Which of the following statements about garbage collection is false?

d. Before destroying an object, the GC calls its Dispose method.

11. Which of the following statements about destructors is false?

c. Destructors are inherited.

12. If a class implements IDisposable, its Dispose method should do which of the following?

d. All of the above.

13. If a class has managed resources and no unmanaged resources, it should do which of the following?

b. Implement IDisposable and not provide a destructor.

14. If a class has unmanaged resources and no managed resources, it should do which of the following?

a. Implement IDisposable and provide a destructor.

Chapter 6: Working with Delegates, Events, and Exceptions

1. Which of the following is a valid delegate definition?

d. private delegate void MyDelegate(float x);

2. Which of the following statements is not true of delegate variables?

a. You need to use a cast operator to execute the method to which a delegate variable refers.

3. If the Employee class inherits from the Person class, covariance lets you do which of the following?

b. Store a method that returns an Employee in a delegate that represents methods that return a Person.

4. If the Employee class inherits from the Person class, contravariance lets you do which of the following?

c. Store a method that takes a Person as a parameter in a delegate that represents methods that take an Employee as a parameter.

5. In the variable declaration Action<Order> processor, the variable processor represents which of the following?

b. Methods that take an Order object as a parameter and return void.

6. In the variable declaration Func<Order> processor, the variable processor represents which of the following?

a. Methods that take no parameters and return an Order object.

7. Suppose F is declared by the statement Func<float, float> F. Then which of the following correctly initializes F to an anonymous method?

d. F = delegate(float x) { return x * x; };

8. Suppose the variable note is declared by the statement Action note. Then which of the following correctly initializes note to an expression lambda?

c. note = () => MessageBox.Show("Hi");

9. Suppose the variable result is declared by the statement Func<float, float> result. Which of the following correctly initializes result to an expression lambda?

d. Both a and c are correct.

10. Which of the following statements about statement lambdas is false?

b. A statement lambda cannot return a value.

11. Suppose the MovedEventHandler delegate is defined by the statement delegate void MovedEventHandler(). Which of the following correctly declares the Moved event?

d. Both b and c are correct.

12. Suppose the Employee class is derived from the Person class and the Person class defines an AddressChanged event. Which of the following should you not do to allow an Employee object to raise this event?

b. Create an OnAddressChanged method in the Employee class that raises the event.

13. Which of the following statements subscribes the myButton_Click event handler to catch the myButton control’s Click event?

a. myButton.Click += myButton_Click;

14. Suppose the Car class provides a Stopped event that takes as parameters sender and StoppedArgs objects. Suppose also that the code has already created an appropriate StoppedArgs object named args. Then which of the following code snippets correctly raises the event?

c. if (Stopped != null) Stopped(this, args);

15. Which of the following statements about events is false?

c. If an object subscribes to an event once and then unsubscribes twice, its event handler throws an exception when the event is raised.

16. Which of the following statements about inheritance and events is false?

a. A derived class can raise a base class event by using code similar to the following:

if (base.EventName != null) base.EventName(this, args);

17. Which of the following statements about exception handling is true?

a. You can nest a try-catch-finally block inside a try, catch, or finally section.

18. Which of the following methods can you use to catch integer overflow exceptions?

d. Either b or c.

19. Which of the following returns true if variable result holds the value float.PositiveInfinity?

d. All of the above.

20. Which of the following statements about throwing exceptions is false?

b. If you rethrow the exception ex with the statement throw, the exception’s call stack is reset to start at the current line of code.

21. Which of the following should you not do when building a custom exception class?

c. Make it implement IDisposable.

Chapter 7: Multithreading and Asynchronous Processing

1. You are a developer at company xyx. You have been asked to improve the responsiveness of your WPF application. Which solution best fits the requirements?

a. Use the BackgroundWorker class.

2. How do you execute a method as a task?

d. All the above.

3. Which of the following is not a locking mechanism?

d. async

4. How can you schedule work to be done by a thread from the thread pool?

c. You call the ThreadPool.QueueUserWorkItem method.

d. You create a new thread and set its property

5. Which of the following are methods of the Parallel class?

b. Invoke

c. For

d. ForEach

6. Which method can you use to cancel an ongoing operation that uses CancelationToken?

b. Call Cancel method on the CancelationTokenSource object that was used to create the CancelationToken

7. Which method would you call when you use a barrier to mark that a participant reached that point?

c. SignalAndWait

8. What code is equivalent with lock(syncObject){…}?

c. Monitor.Enter(syncObject); try{…}finally{ Monitor.Exit(syncObject); }

9. In a multithreaded application how would you increment a variable called counter in a lock free manner? Choose all that apply.

c. Interlocked.Add(ref counter, 1);

e. Interlocked.Increment (ref counter);

10. Which method will you use to signal and EventWaitHandle?

c. Set

Chapter 8: Creating and Using Types with Reflection, Custom Attributes, the CodeDOM, and Lambda Expressions

1. You are given an assignment to create a code generator to automate the task of creating repetitive code. Which namespace contains the types needed to generate code?

d. System.CodeDom

2. Which code can create a lambda expression?

c. x => x * x;

3. You are consulting for a company called Contoso and are taking over an application that was built by a third-party software company. There is an executable that is currently not working because it is missing a DLL file that is referenced. How can you figure out which DLL files the application references?

b. Create an instance of the Assembly class, load the assembly, and call the GetReferencedAssemblies method.

4. You are a developer for a finance department and are building a method that uses reflection to get a reference to the type of object that was passed as a parameter. Which syntax can be used to determine an object’s type?

d. Type myType = myParameter.GetType();

5. You are asked to create a custom attribute that has a single property, called Version, that allows the caller to determine the version of a method. Which code can create the attribute?

b. class MyCustomAttribute : System.Attribute { public string Version { get; set; } }

6. Which class in the System.Reflection namespace would you use if you want to determine all the classes contained in a DLL file?

b. Assembly

7. Which method of the Assembly class allows you to get all the public types defined in the Assembly?

c. GetExportedTypes

8. Which property of the Assembly class returns the name of the assembly?

d. FullName

9. Which method of the Assembly class returns an instance of the current assembly?

a. GetExecutingAssembly

10. Which syntax will Load an Assembly?

a. Assembly.Load("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

b. Assembly.LoadFrom(@"c:\MyProject\Project1.dll");

c. Assembly.LoadFile(@"c:\MyProject\Project1.dll");

d. Assembly.ReflectionOnlyLoad(("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

11. Which method should you call if you want the .NET Framework to look in the load-context to load an Assembly?

c. Load

12. Which method should you call if you want the .NET Framework to look in the load-from context?

b. LoadFrom

13. Which line creates an instance of a DataTable using reflection?

a. myAssembly.CreateInstance("System.Data.DataTable");

14. Which class would you create if you wanted to determine all the properties contained in a class using reflection?

d. Type

15. How can you determine if a class is public or private?

a. Create an instance of the Type class using the typeof keyword and then examine the IsPublic property of the Type variable.

16. Which class in the System.Reflection namespace is used to represent a field defined in a class?

b. FieldInfo

17. Which property of the Type class can you use to determine the number of dimension for an array?

d. GetArrayRank

18. Which statement will returns a private, instance field called "myPrivateField" using reflection? Assume the myClass variable is an instance of a class.

a. myClass.GetType().GetField("myPrivateField", BindingFlags.NonPublic | BindingFlags.Instance)

19. Which method of the MethodInfo class can be used to execute the method?

b. Invoke

20. Which statement uses reflection to execute the method and passes in two parameters given the following code block?

MyClass myClass = new MyClass();

MethodInfo myMethod = typeof(MyClass).GetMethod("Multiply");

c. myMethod.Invoke(myClass, new object[] { 4, 5 });

Chapter 9: Working with Data

1. Which object does the variable mySet inherit from?

Int[] mySet  = new int[5];

c. System.Array

2. Which type should you use to store objects of different types but do not know how many elements you need at the time of creation?

d. ArrayList

3. If you create a custom class that is going to be used as elements in a List object and you want to use the Sort method of the List object to sort the elements in the array, what steps must you take when coding the custom class?

b. Inherit from the IComparable interface.Implement the CompareTo method.

4. Which collection would you use if you need to process the items in the collection on first-in-first-out order?

b. Queue

5. Which collection would you use if you need to process the items in the collection on a last-in-first-out order?

c. Stack

6. Which collection would you use if you need to quickly find an element by its key rather than its index?

a. Dictionary

c. SortedList

7. Which ADO.NET object is used to connect to a database?

b. Connection

8. Which properties of an ADO.NET Command object must you set to execute a stored procedure?

c. CommandTypeCommandTextParameters

9. Which Command object’s method would you use to execute a query that does not return any results?

a. ExecuteNonQuery

10. Which Command object’s method would you use to execute a query that returns only one row and one column?

c. ExecuteScalar

11. Which ADO.NET object is a forward only cursor and is connected to the database while the cursor is open?

a. DBDataReader

12. Which ADO.NET Command object’s property would you use when a query returns the SUM of a column in a table?

c. ExecuteScalar

13. Which ADO.NET object is a fully traversable cursor and is disconnected from the database?

c. DataTable

14. Which method of a DataAdapter is used to populate a DataSet?

b. Fill

15. Which property of an ADO.NET DataAdapter is used to insert records in a database?

c. InsertCommand

16. Which ADO.NET Command object’s property would you use when a query returns the SUM of a column in a table?

c. ExecuteScalar

17. When using the ADO.NET Entity Framework you create a Model that represents the object in the database. What class does the Model inherit from?

a. DBContext

18. How are stored procedures represented in the ADO.NET Entity Framework?

b. A method is added to the Model that is the same name as the stored procedure.

19. Which code uses the ADO.NET Entity Framework to add a record to the database?

a.

using (NorthwindsEntities db = new NorthwindsEntities())

{

    Category category = new Category()

    {

        CategoryName = "Alcohol",

        Description = "Happy Beverages"

    };

    db.Categories.Add(category);

    db.SaveChanges();

}

20. Which code uses the ADO.NET Entity Framework to update a record in the database?

c.

Category category = db.Categories.First(c => c.CategoryName == "Alcohol");

category.Description = "Happy People";

db.SaveChanges();

Chapter 10: Working with Language Integrated Query (LINQ)

1. Which answer has the correct order of keywords for a LINQ query expression?

c. from, where, select

2. Which where clause can select all integers in the myList object that are even numbers given the following from clause?

from i in myList

c. where i % 2 == 0

3. Which line of code executes the LINQ query?

[1] var result = from i in myArray

[2] order by i

[3] select i

[4] foreach(int i in result)

[5] { …}

d. Line 4

4. Which method can you use to find the minimum value in a sequence?

a. (from i in myArray select i).Min()

5. Which methods can you use to find the first item in a sequence?

b. First

d. Take

6. Which where clause returns all integers between 10 and 20?

b. where i >= 10 && i <= 20

7. Which clause orders the state and then the city?

c. orderby h.State, h.City

8. Which statement selects an anonymous type?

c. select new { h.City, h.State }

9. Which on statement joins two sequences on the StateId property?

a. on e.StateId equals s.StateId

10. Which two keywords must you use in a join clause to create an outer join?

b. into, DefaultIfEmpty

11. Which join clause uses a composite key?

a. on new { City = e.City, State = e.State } equals new { City = h.City, State = h.State }

12. Which statement groups a sequence by the State property?

c. group e by e.State

13. Which answers return the count of all even numbers?

a. myArray.Where(i => i % 2 == 0).Count()

b. myArray.Count(i => i % 2 == 0)

Chapter 11: Input Validation, Debugging, and Instrumentation

1. If the user is typing data into a TextBox and types an invalid character, which of the following actions would be inappropriate for the program to take?

d. Display a message box telling the user that there is an error.

2. If the user types an invalid value into a TextBox and moves focus to another TextBox, which of the following actions would be inappropriate for the program to take?

a. Force focus back into the TextBox that contains the error.

3. If the user enters some invalid data on a form and then clicks the form’s Accept button, which of the following actions would be appropriate for the program take?

d. All the above.

4. Which of the following methods returns true if a regular expression matches a string?

b. Regex.IsMatch

5. Which of the following regular expressions matches the Social Security number format ###-##-#### where # is any digit?

c. ^\d{3}-\d{2}-\d{4}$

6. Which of the following regular expressions matches a username that must include between 6 and 16 letters, numbers, and underscores?

b. ^[a-zA-Z0-9_]{6,16}$

7. Which of the following regular expressions matches license plate values that must include three uppercase letters followed by a space and three digits, or three digits followed by a space and three uppercase letters?

a. (^\d{3} [A-Z]{3}$)|(^[A-Z]{3} \d{3}$)

8. Which of the following statements about assertions is true?

d. All the above.

9. Which of the following statements about the Debug and Trace classes is true?

b. The Debug class generates messages if DEBUG is defined. The Trace class generates messages if TRACE is defined.

10. Which of the following statements about builds is true by default?

a. Debug builds define the DEBUG symbol.

b. Debug builds define the TRACE symbol.

d. Release builds define the TRACE symbol.

11. Which of the following statements about PDB files is false?

b. You can use a PDB file to debug any version of a compiled executable.

12. Which of the following statements about tracing and logging is false?

d. A program cannot write events into the system’s event logs, so you can see them in the Event Viewer.

13. Which of the following methods would probably be the easiest way to find bottlenecks in a program if you had no idea where to look?

a. Use an automatic profiler.

14. What of the following is the best use of performance counters?

b. To determine how often a particular operation is occurring on the system as a whole.

Chapter 12: Using Encryption and Managing Assemblies

1. You are a developer at company xyx. You have been asked to implement a method to safely save and restore data on the local machine. What kind of algorithm best fits the requirements?

a. Symmetric algorithm

2. You are a developer at the company xyx. You have been asked to implement a method to safely send data to another machine. What kind of algorithm best fits the requirements?

b. Asymmetric algorithm

3. You are a developer at the company xyx. You have been asked to implement a method to handle password encryption without offering the possibility to restore the password. What kind of algorithm best fits the requirements?

c. Hashing algorithm

4. Which of the following code snippets will you use to calculate the secure hash of a byte array called userData? If you already have created an algorithm object called sha.

b. sha.ComputeHash(userData);

5. Which of the following code snippets will you use to encrypt an array called userData that can be decrypted by anyone logged in on the current machine, and without using any entropy?

b. ProtectedData.Protect(userData, null, DataProtectionScope.LocalMachine);

6. Which of the following code will you use to encrypt an array called encryptedData that can be encrypted by the current user, and without using any entropy?

a. ProtectedData.Unprotect(encryptedData, null, DataProtectionScope.CurrentUser);

7. What describes a strong name assembly?

f. All the above

8. How can you deploy a strong named assembly?

a. By running gacutil.exe

b. By creating an installer

d. By copying the file to the Bin folder of the application

9. How can you deploy a private assembly?

b. By adding a reference to the assembly in Visual Studio

c. By copying the file in the Bin folder of the application

10. What is a strong name assembly?

e. A signed assembly