C# Certification Flashcards

70-483 Certification Exam Review (892 cards)

1
Q

Suppose you are developing an application which stores a user’s browser history. Which collection class will help to retrieve information of the last visited page?

A

Last visited (LIFO= Stack)

Answer = Stack

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

The following code is boxed into object o.

double d = 34.5;
object o = d;

You are asked to cast “object o” into “int”.

A

The object needs to be cast to double
Because it is a decimal value need to cast to float
Finally cast to int

Answer = int i = (int)(float)(double)o;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

You are developing a game that allows players to collect from 0 through 1000 coins. You are creating a method that will be used in the game. The method includes the following code. (Line numbers are included for reference only)

01 public string FormatCoins(string name, int coins)
02 {
03
04 }

The method must meet he following requirements:

  1. Return a string that includes the player name and the number of coins
  2. Display the number of coins without leading zeros if the number is 1 or greater
  3. Display the number of coins as a single 0 if the number is zero

You need to ensure that the method meets the requirements. Which code segment should you insert at line 03

A

Format specifier D formats integer digits with optional negative sign.

Answer = string.Format($”Player {name}, collected {coins:D3} coins”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you encapsulate an array of integers into an indexer?

A

private int[] array;

public int this[int index]
{
  get {return array[index];}
  set { array[index] = value;}
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Is the following method “Display” considered to be overloaded?

class Person
{
  public void Display()
 {
 }

public int Display()
{
}
}

A

No

Overloading refers to different parameter types. The display method has different return types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Suppose you’re creating a class named Player. The class exposes a string property named HitSpeed. Here is the code snippet of player class.

01 class Player
02 {
03   public int HitSpeed
04   {
05     get;
06     set;
07   }
08 }

The HitSpeed property must meet the following requirements:

  1. The value must be accessed by code within the Player class
  2. The value must be accessed to derived classes of Player
  3. The value must be modified only by code within the Player class.

You need to ensure that the implementation of the EmployeeType property meets the requirements. Which code segment you should replace at line 05, and 06?

A

protected get;

private set;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Suppose you are developing an application. The application has two classes named Player and Person.

The Player class must meet the following requirements

  1. It must inherit from the Person class
  2. It must not be inheritable by other classes in the application.

Which code segment should you use?

A
sealed class Player : Person
{

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Suppose you are developing an application that includes the following code segment.

interface ICricket
{
  void Play();
}

interface IFootball
{
}

You need to implement both Play() methods in a derived class named Player that uses the Play() method of each interface.

A
class Player : ICricket, IFootball
{
  // Both ICricket and IFootball have play methods
  // Must be declared explicitly
  void ICricket.Play()
  {
  }
  void IFootball.Play()
  {
  }
}

Player player = new Player();
( (ICricket)player ).Play();
( (IFootball)player).Play();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
Which type cannot be instantiated?
A enum type
B static type
C class type
D System.Object type
A

B. Static type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which operator is used to get instance data inside type definition?

A

this

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the code segment for defining implicit type conversion for a Person class?

A
class Person
{
  public string name;
  public int age;

public static implicit operator Person(string n)
{
Person person = new Person{age=0, name=n};
return person;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Which operator is used to compare types?

A) as
B) is
C) this
D) ?

A

B) is

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Suppose you are developing an application that saves age values in integers

int age = 22;

You are asked to provide the right code snippet for defining the extension method for age.

A
static class Extension
{
 public static void ExtensionMethod(this int i)
 {

}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Which jump statement will you use to start the next iteration while skipping the current iteration of loop?

A

Continue

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

You need to use null-coalescing operator to make sue “name” variable must have a value not null.

What is the right way to use null-coalescing operator in C#?

A

string name = n??”No Name”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

You are developing an application that saves user’s information. The application includes the following code segment (line numbers included for reference).

01 public bool IsNull(string name)
02 {
03 return true;
04 }

You need to evaluate whether a name is null

What code segment should be inserted at line 03.

A

I would do this….

return string.IsNullOrWhiteSpace(name) ? false: true;

or

return name==null?false: true;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Suppose you are implementing a method name “Show” that will be able to take an unlimited number of int arguments. How are you going to define its method signature.

A

void Show(params int[] arg)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Which of the following methods help us to convert string type data into integers?

Select any two

A) Convert.toInt32();
B) Convert.Int32();
C) int.parse();
D) parse.int();

A

A) Convert.toInt32()

C) int.parse()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What collections stores values in Key, Value pairs?

A

Dictionary
SortedList
HashTable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

To control how objects are compared, what interface is implemented

A

IComparable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Last In, First Out data structures are represented as?

A

Stack

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

First In, First Out structures are represented as?

A

Queue

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

When are generic collection classes appropriate?

A

When all objects are of the same type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What namespace is inherited by the following data structures?

Dictionary
List
Queue
Stack
SortedList
A

System.Collections.Generic

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What namespace is inherited by the following data structures? ``` ArrayList HashTable Queue Stack SortedList ```
System.Collections
26
Arrays inherit from what namespace?
System.Array
27
What object used with a DataSet is used to add, update or delete records from a database?
DataAdapter
28
How is a dataset populated with data?
using the DataAdapter
29
What is a DataSet
A disconnected resultset that contains one or more data tables
30
What method returns the data represented as XML
ExecuteXMLReader
31
What method is used to return a single value from a database such as when a query returns a Sum or Count
ExecuteScalar
32
What object is a read-only, forward-only cursor connected to the database?
DBDataReader
33
What method is used to execute non-result returning queries such as Insert, Update or Delete
ExecuteNonQuery
34
What object is used to call a stored procedure or execute a dynamic SQL statement?
The Command object
35
What is ADO.Net?
A set of classes used to execute commands on a database
36
An ORM tool that masks the syntax for using ADO.Net to communicate with a database is referred to as?
Entity Framework
37
Classes are representative of what within Entity Framework Model
objects in the database
38
Within the Entity Framework Model, stored procedures are represented as what?
Methods
39
How are parameters passed by WCF Data Services to query a database?
By passing the parameters within the URL query string
40
What data formats are returned by WCF Data Services?
OData Adam | JSON
41
What protocol is used by WCF Data Services?
OData
42
What purpose does the await command serve?
Kicks off the method and returns processing to the calling method until the method completes
43
The async keyword must modify what in order to use the await keyword?
The method signature
44
In C# 5.0 and later, what keywords are used to perform asynchronous operations?
asynch & await
45
What classes are used to read and write string data
StringWriter | StringReader
46
Name three methods used by StreamReader to get the contents of a file.
Character by Character Line by Line Entire File at once
47
What is the default character encoding for StreamReader and StreamWriter
UTF-8
48
What classes are used for reading and writing characters by using an encoded value to convert the characters to and from bytes?
StreamReader | StreamWriter
49
What classes are used for reading or writing binary values?
BinaryReader | BinaryWriter
50
What object is used to represent the contents of a file in memory and can be used to write data or read data from a file.
Stream
51
What objects are used to determine properties of a file and also performs operations on a file
File and FileInfo
52
In LINQ, what is an outer sequence?
The sequence calling the Join method
53
A feature of LINQ that uses extension methods on types that implement the IEnumerable or IQueryable interface to query the data is a ..?
Method based query.
54
LINQ statements executed in a where clause for a query expression is called it's..?
Predicate
55
LINQ statements that select a subset of properties from a type that creates a new anonymous type is referred to as ?
Projection
56
A feautre of LINQ that enables you to query any type that implements the IEnumerable or IQueryable interface is called?
Query expression
57
A set of features that extends query capabilities to C# is called?
Language Integrated Query or LINQ
58
In LINQ, what is an inner sequence?
When using a method based join, the sequence passed to the join as a parameter.
59
A variable that has its type determined by the expression on the right side of the initialization statement and using the keyword var is .. .?
Implicitly typed
60
What operator is the"goes to" or "such that" operator?
=> | Used primarily in lambda expressions
61
Execution of a LINQ query is deferred until the result is enumerated. This is referred to as ?
Deferred execution
62
Define a composite key
Contains multple properties that are needed to complete a join.
63
A type created with read-only properties without having to write the code to declare the class is referred to as an....?
Anonymous type
64
What class is used in a LINQ to XML query to return the result of a query in XML?
XElement
65
What LINQ method allows you to return a distinct list of elements from a sequence?
Distinct
66
What LINQ method allows you to return a limited number of elements from a sequence.
Take
67
What LINQ method allows you to skip a specific number of elements in a sequence?
Skip
68
In LINQ, how are two sequences concatenated?
Concat
69
When using method based LINQ queries, how are out joins formed?
GroupJoin
70
In LINQ, what is the purpose of the SelectMany method?
To flatten two sequences into one result, similar to join.
71
Which LINQ query uses lambda expressions as parameters to methods?
Method based queries
72
What is the difference between method based queries and query expressions?
Syntax, no functional difference.
73
In LINQ, a group by clause returns what data type?
IGrouping
74
How is a LINQ composit key formed?
By specifying an anonymous type in the join clause
75
In LINQ, how are outer joins formed?
1) Include an INTO clause in your join | 2) Call the Default ifEmpty to set properties when no match is found.
76
What keyword is used to join properties in LINQ?
Equals
77
Define projection
Creating a custom type in a select clause of a query expression using a limited number of properties from the original object.
78
What query expression clause is used to sort the results on one or more properties?
OrderBy
79
How are multiple where clauses implemented using LINQ?
By using the && operator
80
Define the predicate in LINQ
All code contained within the Where clause
81
How are joins evaluated in LINQ queries?
Joins are always equivalence based
82
How is the execution of a LINQ query forced?
By using any of the aggregate functions or populating a list or array using toList() or toArray()
83
When does execution of a LINQ query occur?
When the result is enumerated
84
Define a LINQ clause
A query expression containing Select, GroupBy, Where or joins
85
By convention, the results of a LINQ query are stored where?
To a variable of type var, allowing the result to be implicitly typed.
86
What object can be queried by LINQ?
Any object that implements IEnumerable or IQueryable
87
Define the correct order of keywords for a LINQ query expression.
from... where ... select ...
88
Define a statement that returns the count of all even numbers
``` var count = myNumbers.Where(i => i %2 == 0) .Count() ```
89
Define a statement that groups a sequence by the State property
var states = myStates.GroupBy(s => s.name);
90
Define a statement that creates an anonymous type
.Select( new {h.city, h.state})
91
What two keywords must you use in a join clause to create an outer join?
into | DefaultIfEmpty
92
Define a clause that joins two sequences on the stateId property
on e.stateId equals s.stateId
93
Define a join clause that uses a composite key
on new {City = e.City, State = e.State} equals new {City = h.City, State = h.State}
94
Define a LINQ clause that orders by state and then by city
Orderby h.state, h.city
95
Define a WHERE clause that returns all integers between 10 and 20
Where i >= 10 && i <= 20
96
Define the extension LINQ method used to find the first item in a sequence
First or Take
97
Define how to find the minimum value in a sequence
(from i in myArray | selecti).Min()
98
Given: var result = from i in my Array order by i select i; ``` foreach(int i in result) { // Do something } ``` Where is the LINQ query executed?
When enumerating the foreach statement
99
# Define a WHERE clause that selects all integers in a myList object that are even number given from i in myList
Where i % 2 == 0;
100
Name two methods of performing customized serialization
Attributes (the preferred method) | Implement Iserializable
101
What class is used to perform binary serialization.
BinaryFormatter
102
XML serialization is performed by what class?
XMLSerializer
103
What class is used to perform JSON serialization
DataContractJsonSerializer
104
What is serialization?
The process of transforming an objects data to persisted storage or to transfer the object from one domain to another
105
A set of classes in the .NET framework that enables you to convert to a database, retrieve data, execute stored procedures, add, update, or delete records in a table called?
ADO.NET
106
What is the object relationship mapping tool that provides a graphical interface that generates code to perform operations against a db using ADO?
ADO.NET Entity Framework
107
The most basic type used to store a set of data is called?
Array
108
What is the role of the keyword async?
Indicates that the method, lambda expression, or anonymous method is asynchronous
109
What keyword suspends the execution of a method until the awaited task completes?
await
110
The process of converting a reference type to a value type is called?
unboxing
111
What is boxing?
The process of converting a value type to a reference type
112
What is a collection?
A generic term encompassing lists, dictionaries, queues, stacks, hash tables and other objects that contain sets of data.
113
The object in ADO.NET that allows you to open and execute commands against a database is called?
A connection object.
114
What is the IComparable interface?
Implements an interface that can be sorted when used in a collection or array.
115
A method that is used when referencing an element in an array or collection by using square brackets[] and it's index is called?
indexer
116
What is JSON?
JavaScript Object Notation A lightweight data-interchange format
117
A computer software term for tools that convert data between type systems using an object oriented programming language is called?
ORM Object Relational Mapping
118
The XML representation of data returned from an OData query is called?
OData ATOM
119
What is OData?
Open Data Protocoal A web protocol for querying and updating data over the intranet or internet
120
Creating a new copy of an object that copies all value types and copies object references for reference types is called a ?
shallow copy
121
The process of converting an object into a stream of bytes that can be stored or transmitted is called?
serialization
122
Define stream.
An abstract class that provides a generic view of a sequence of bytes.
123
What is a T4 template?
A file that contains text blocks and control statements that enable you to generate a code file.
124
What enables you to use OData to expose and consume data over the web or intranet?
WCF Data Services WCF=(Windows Communication Foundation)
125
You are working with a large group of family objects. You need to remove all duplicates and then group them by last name. Which collections should you use?
List to hold the original objects Dictionary to remove duplicates and create key of last names.
126
You are using a queue and you want to add a new item. Which method do you use?
Enqueue
127
You want to store a group of orders and make sure that a user can easily select an order by it's order number. Which collection do you use?
Dictionary
128
What must be implemented when creating custom collections?
Both IEnumerable and IEnumerable
129
What collection stores values in memory as a last-in-last-out structure?
Stack, Stack
130
What collection stores value in memory as a first-in-first-out structure?
Queue, Queue
131
What collection stores unique items and offer set operations?
HashSet
132
What is a dictionary?
A collection that stores and accesses items via key/value pairs.
133
What is the most used collection?
List, List
134
Define an Array
The most basic collection type which is constrained by a fixed size
135
When given the opportunity to use the generic or non-generic collection, which is generally preferred?
Always use generic where possible.
136
You want to serialize some data to XML, and you need to make sure that a certain property is NOT serialized. Which attribute should you use?
XMLIgnore
137
You are serializing some sensitive data to a binary format. What should you use?
BinaryFormatter to put the data in binary format. ISerializable to protect sensitive data.
138
JSON text formatted files are created in .NET using what class?
DataContractJsonSerializer
139
You need to store a large amount of data and you want to do this in the most optimal way. What serializer should you use?
BinaryFormatter
140
WCF serialization is performed using what class?
DataContractJsonSerializer
141
How is binary serialization performed in .NET?
Using the BinaryFormatter class
142
How is the XMLSerializer configured?
Through the use of attributes.
143
What class handles XML serializtion?
XMLSerializer
144
What is deserialization
Takes a series of bytes or a flat file and transforms it to an object
145
What is serialization?
The process of transforming an object to a flat file or series of bytes
146
Given query ``` var query = from p in myContext.Products where p.price < 50 select p; int numberOfItems = query.Count(); var products = query.ToList(); ``` How can you improve performance?
Use paging to limit the number of items retrieved And Avoid hitting the database multiple times
147
You are trying to use a LINQ query but receiving a compile error that the Where method cannot be found. What steps should you take?
1. verify using System.Linq | 2. Validate the datatype implements IEnumerable, IEnumerable
148
You have a list of data you want to filter the dates to the current year and then select the highest date. Create the query.
DateTime result = dates.Where( d => d.Year == DateTime.Now.Year) .OrderByDescending( d=>d) .FirstOrDefault();
149
When are LINQ queries executed?
Not until they are first iterated, known as deferred execution.
150
What is the primary function of LINQ?
To provide a uniform way of writing queries against multiple data stores.
151
Which ADO.NET command objects's property would you use when a query returns the sum of a column in a table?
ExecuteScalar
152
Which property of an ADO.NET DataAdapter is used to insert records in a database?
InsertCommand
153
Which method of a DataAdapter is used to populate a DataSet?
Fill
154
Which ADO.NET object is fully traversable cursor and is disconnected from the database?
DataTable
155
Which ADO.NET command object's property would you use when a query returns the sum of a column in a table?
ExecuteScalar
156
Which ADO.NET object is a forward-only cursor and is connected to the database while the cursor is open?
DBDataReader
157
using ADO.NET Entity Framework how is a record updated in the database?
Category category = db.Categories.First( c => c.CategoryName = "alcohol"); category. Description = "Happy Please"; db. SaveCjhanges();
158
Using ADO.NET Entity Framework, how is a record added to the database?
``` using(NorthwindsEntitities db = new NorthwindEntities()) { Category category = new Category() { category = "Alcohol", description = "beverage" } ``` db.Categories.Add(category); db.SaveChanges(); }
159
How are stored procedures represented in the ADO.NET Entity Framework?
A method is added to the model that is the same name as the stored procedure.
160
When using the ADO.NET Entity Framework you create a model that represents the object in the databases. What class does the model inherit from?
DBContext
161
Which command object's method would you use to execute a query that returns only one row and one column?
ExecuteScalar
162
Which command object's method would you use to execute a query that does not return any results?
ExecuteNonQuery
163
Which properties of an ADO.NET command object must you set to execute a stored procedure?
CommandType CommandText Parameters
164
Which ADO.NET object is used to connect to a database?
Connection
165
Which collection would you use if you need to quickly find an element by its key rather than it's index?
Dictionary or SortedList
166
Which collection would you use if you need to process the items in the collection on a last-in, first-out order?
Stack, Stack
167
Which collection would you use if you need to process the items in the collection on first-in, first-out order?
Queue, Queue
168
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?
1. Inherit from IComparable | 2. Implement CompareTo()
169
Which type should you use to store objects of different types but do no know how many elements you need at the time of creation?
ArrayList
170
Which object does the variable mySet inherit from? int[] mySet = new int[5];
System.Array
171
Custom collections must inherit from which base class?
CollectionBase
172
What is SSL?
Secure Socket Layer is a cryptographic protocol used for secure communication over the internet.
173
Define secured hash algorithm
SHA is a family of cryptographic algorithms used to calculate hashes published by NIST
174
What is the infrastructure required to handle digital certificates?
Public Key Infrastructure (PKI)
175
A family of cryptographic algorithms used to provide data integrity and authenticity is called?
Message Authentication Code (MAC)
176
What is the Just In Time (JIT) compiler?
A component of the .NET that transforms the IL into binary code that can be run on the target platform.
177
The result of compiling a .NET application from source code is called the?
Intermediate Language (IL)
178
A data array used by the encryption algorithm to encrypt the first data block is referred to as the?
Initialization Vector (IV)
179
Describe hashing.
Used to map data structures of variable length to fixed size data structures.
180
A data structure that holds items that share the same hash value is called?
Hash Bucket
181
What is the Global Assembly Cache?
The GAC is a machine-wide code cache
182
The process of decoding previously encrypted data so that it can be used by your application is?
Decryption
183
The process of encoding data so that it cannot be read by an unauthorized person is called?
Encryption
184
The practice and study of techniques for secure communication is called?
Cryptography
185
A list of digital certificates that have been revoked for various reasons is referred to as?
Certificate Revocation List (CRL)
186
Define the CLR
The Common Language Runtime is the component of the .NET Framework responsible for running .NET applications and managing the running environment.
187
Define Certificate Stores
A special storage location on your computer, used to store encryption certificates
188
What entity issues digital certificates?
Certificate Authority (CA)
189
Define asymmetric encryption
A criptographic algorithm that uses two complimentary keys. One for encryption and one for decryption.
190
What is an assembly?
An assembly is the unit of reuse, deployment, versioning and security.
191
You need to process a large number of XML files ina scheduled service to extract some data. Which class should you use?
Because data is only being extracted, use XmlReader
192
You are planning to build an application that will use an object-oriented design. It will be used by multiple users at a time. Which technology should you use?
An ORM such as Entity Framework
193
You want to update a specific row in the database. What commands are required?
1. SqlConnection to establish connection to database | 2. SqlCommand to execute the query
194
Name the four classes used to manipulate XML.
XmlReader XmlWriter XPathNavigator XmlDocument
195
Why should you use parameterized queries when performing CRUD operations?
To avoid Sql injection
196
Under ADO.NET, how are connections made to the database?
Using the DBConnection object
197
What is ADO.NET?
A provider model that enables you to connect to different types of databases.
198
You are writing an application that will be deployed to western countries. It outputs user activity to a text file. Which encoding should you use?
UTF-8
199
You have built a complex calculation algorithm. It takes quite some time to complete and you want to make sure that your application remains responsive, what do you do?
Task.Run() The process will run on a background thread
200
You are creating a new file to store some log data. Each time a new log entry is necessary, you write a string to the file. Which method should you use?
File.AppendText
201
What namespace supports WebRequest and WebResponse?
System.Net
202
What classes are used for performing network requests?
WebRequest | WebResponse
203
What class implementation is used for dealing with files, network operations and other types of IO
Stream
204
Define streams
An abstract method for working with a series of bytes
205
What methods are available to create and parse file paths?
static Path class
206
What methods are provided to work with files?
File | FileInfo
207
How are folders manipulated programmatically?
Directory | DirectoryInfo
208
How are drives manipulated programmatically?
Drive | DriveInfo
209
Write code to decrypt an array called encryptedData that was encrypted by the current user and without using entropy
ProtectedData.Unprotect( encryptedData, null, DataProtectionScope.CurrentUser);
210
What is a strong name assembly?
A signed assembly
211
How can you deploy a private assembly?
By copying the file to the bin folder or Adding a reference to the assembly via Visual Studio
212
How can you deploy a strong named assembly?
``` Run gacutil.exe or copy file to bin folder or create an installer ```
213
Describe the components of a strong named assembly
``` Name Version Public Key Token Culture Processing Architecture ```
214
Write a code snippet to encrypt an array called userData that can be decrypted by anyone logged in on the current machine without using any entropy.
ProtectedData.Protect(userData, null, DataProtectionScope.LocalMachine);
215
Write a code snippet to calculate the secure hash of a byte array called userData using the SHA algorithm
sha.ComputeHash(userData);
216
You are a developer at company xyz. You have been asked to implement a method to handle password encryption without offering the possibility to restore the password What algorithm fits the requirement?
Hashing algorithm
217
You are a developer at company xyz. You have been asked to implement a method to safely send data to another machine. What kind of algorithm best fits the requirement?
Asymmetric algorithm
218
You are a developer at company xyz. 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?
Symmetric algorithm.
219
When is a MAC algorithm recommended?
To ensure both authenticity and integrity is required
220
When is the hashing algorithm recommended?
When data integrity is the only requirement
221
When is asymmetric encryption recommended?
If you do not have a way to send data securely
222
When is symmetric encryption the best option?
IF you need to encrypt data locally or you have a secure way to distribute the encryption key.
223
How is the encryptor/decryptor used?
Directly, using TransformFinalBlock or sending to CryptoStream
224
How is symmetric encryption instantiated?
By calling CreateEncryptor CreateDecryptor
225
What is required to perform symmetric encryption?
An initialization vector (IV) used to encryp the first block of data.
226
Define symmetric encryption
Encryption based on a shared secret
227
How many keys are used in asymmetric encryption?
Two 1. Private key 2. Public key
228
Define asymmetric encryption
Based on a pair of complimentary keys. Data encrypted by one key can be decrypted by the other.
229
Write a regular expression that 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.
(^d{3} [A-Z] {3}$) | (^[A-Z]{3} \d{3}$)
230
Write a regular expression that matches a username that must include between 6 and 16 letters, numbers and underscores
^[a-zA-Z0-9_]{6,16}$
231
Write a regular expression matching the social security number format ###-##-#### where # is any digit.
^\d{3}-\d{2}-\d{4}$
232
What method returns true if a regular expression matches a string?
Regex.IsMatch
233
What is the best use of performance counters?
To determine how often a particular operation is occurring on the system as a whole.
234
True or False Whan an assertion fails in debug builds, the Debug.Assert method allows you halt, debug the program or continue running?
True
235
True or False The program must continue running even if a Debug.Assert method stops the program
True
236
True or False The Debug.Assert method is ignored in release builds
True
237
What builds define the TRACE symbol?
Debug and Release
238
What builds define the Debug symbol
Debug
239
How can you prevent Visual Studio from creating a .pdb file?
Setting the value of PDB file type to "None"
240
What file is required to debug a compiled executable?
.pdb file
241
What statements are used to trace or log a program's execution?
DEBUG and TRACE
242
The process of making the program record key events in a log file is referred to as?
logging
243
The process of instrumenting a program to track what is doing is referred to as ?
Tracing
244
What method would you use to investigate bottlenecks in a program?
Use an automatic profiler
245
What statement can be used to validate data as it moves through a program?
Debug.Assert
246
How are preprocessor symbols disabled?
#UNDEF
247
What processor directives define preprocessor symbols?
#DEFINE
248
How can you determine what code is included in a program?
``` By using directives #if #elif #else #endif ```
249
What is the purpose of the #line directive?
To change the line number or name of file reported as errors
250
How are custom warnings and/or errors added to the error list?
by using #warning or #error
251
What is the syntax to create collapsible code regions?
``` #region .. #endregion ```
252
What is the syntax to disable a warning?
#pragma warning disable
253
What is the syntax to restore a warning?
#pragma warning restore
254
Where is the predefined constant TRACE defined?
In the debug and release builds
255
Where is the predefined constant DEBUG defined?
In the debug builds
256
Calls to DEBUG and TRACE are ignored if?
Both DEBUG and TRACE are not defined
257
Useful DEBUG and TRACE methods include?
``` Assert Fail Flush Indent Unindent Write WriteIf WriteLine WriteLineIf ```
258
When adding standard listeners to Debug and Trace objects, where are messages written to?
1. Output window 2. Event logs 3. Text files
259
What file is used to debug a compiled executable?
.pdb
260
What directives are used to implement tracing?
DEBUG and TRACE
261
Instrumenting a program to trace it's progress is known as?
Tracing
262
Name the methods to support logging
1. Writing to a text file 2. Using DEBUG and TRACE with a listener to write to a text file 3. Writing to an event log
263
The recording of key events is known as?
logging
264
What methods are used to support profiling?
1. Using a profiler 2. Instrumenting code by hand 3. Performance counters
265
Gathering information about a program to study characteristics such as speed and memory usage is referred to as?
Profiling
266
A test on data ot see if the data makes sense is referred to as a ?
sanity check
267
What is tracing?
The process of instrumenting a program so that you can track what it is doing
268
What is a regular expression?
An expression in regular expression language that defines a pattern to match.
269
What is profiling?
The process of instrumenting a program to study it's speed, memory, disk usage, or other performance characteristics.
270
An automated tool that gathers performance data for a program by it's code or by sampling is referred to as?
a profiler.
271
What is a performance counter?
A system-wide counter used to track some type of activity on the computer.
272
A regular expression used for matching parts of a string is called?
a pattern
273
What is logging?
The process of instrumenting a program so it records key events?
274
Adding features to a program to study the program itself is called?
instrumenting
275
Options set in a regular expression using the syntax | (?imasx) are referred to as ?
inline options
276
A sequence of characters that have special meaning in a regular expression is referred to as a ?
escape sequence
277
Define data validation
Program code that verifies that a data value makes sense
278
A predefined symbol created by Visual Studio that you can use with #if, #elif, #else and #endif directives to determine what code is in the program?
Conditional Compilation Constant
279
A regular expression construction that represents a set of characters to match is?
character class
280
A piece of code that makes a particular claim about data and throws an exception if that claim is false is called?
An assertion
281
What method is used to create assertions?
System.Diagnostics.Debug.Assert
282
Given the following: MyClass myClass = new MyClass(); MethodInfo myMethod = typeof(MyClass).GetMethod("Multiply"); using reflection, execute the method and pass in two parameters.
myMethod.Invoke(myClass, | new object[]{4,5});
283
Which method of the MethodInfo class can be used to execute the method using reflection?
Invoke
284
Assume myClass is an instance of a class. Create a statement that returns a private instance field called "myPrivateInstance" using reflection.
MyClass.GetType().GetField("myPrivateField", BindingFlags.NonPublic | BindingFlags.Instance);
285
Which property of the Type class can you use to determine the number of dimensions in an array?
GetArrayRank
286
Which class in the System.Reflection namespace is used to represent a field defined in a class?
FieldInfo
287
Using reflection, how an you determine if a class is public or private?
Create an instance of the Type class using typeof() and then examine the IsPublic propery of the Type variable
288
Which class would you create if you wanted to determine all properties contained in a class using reflection?
Type
289
Create an instance of a DataTable using reflection
myAssembly.CreateInstance("System.Data.DataTable");
290
Which method should you call if you want .NET Framework to look in the load-from context?
LoadFrom
291
Which method should you call if you want the .NET Framework to look in the load-context to load an Assembly?
Load
292
Define the syntax to load an assembly
1. Assembly.Load("System.Data", Version=4.0.0.0, Culture = neutral, PublicKeyToken=b77a5c561934e089); 2. Assembly.LoadFrom(@"c:\myProject\Project1.dll"); 3. Assembly.LoadFile(@"c:\myProject\Project1.dll"); 4. Assembly.ReflectionOnlyLoad("System.Data", Version=4.0.0.0, Culture = Neutral, PublicKeyToken=b77a5c561934e089);
293
Which method of the Assembly class returns an instance of the current assembly?
GetExecutingAssembly
294
Which property of the Assembly class returns the name of the assembly?
FullName
295
Which method of the Assembly class allows you to get all the public types defined in the assembly?
GetExportedTypes
296
Which class in the System.Reflection namespace would you use if you want to determine all the classes contained in the .dll file?
Assembly
297
You are asked to create a custom attribute that has a single property, called version, that allows the caller to determine the version of the method. Which code creates the attribute?
``` class MyCustomAttribute:System.Attribute { public string Version{get; set;} } ```
298
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 passed as a parameter. Which syntax is used to determine object type?
Type myType = myParameter.GetType();
299
You are consulting for a company called Contoso and are taking over an application that was built by a third party. How can you figure out which .dll files are being referenced?
1. Create an instance of the assembly class 2. Load the assembly 3. Call the GetReferencedAssemblies method
300
What code creates a lambda expression returning the squares of an integer?
x => x * x;
301
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?
System.CodeDom
302
The process that permits parameter types that are less derived than the delegate type?
Contravariance
303
The process that enables you to have a method with a more derived return type than the delegate return type is ?
Covariance
304
The => symbol in a lambda expression is referred to as?
goes to or such that
305
What is a delegate?
A type that references a method
306
Shorthand syntax for anonymous functions are referred to as?
lambda expressions
307
What class generates the class file in either C#, VB or JScript?
System.CodeDom.CodeDomProvider
308
In the codeDom, what class is the top level class?
System.CodeDom.CodeCompileUnit
309
What is the CodeDom?
Code Document Object Model As set of classes that enables you to create code generators
310
Custom attributes inherit from what class?
System.Attribute
311
How is an attribute declared?
By decorating with square brackets []
312
What enables you to create metadata for a class, property or method?
Attributes
313
What method returns a PropertyInfo object and enables you to set or get a property's value?
Type.GetProperty
314
What does System.Type represent?
A class, interface, array, value type, enumeration, parameter, generic type definition and open or closed generic types.
315
What method creates an instance of a type?
Assembly.CreateInstance
316
What method loads the assembly but does not enable execution?
Assembly.ReflectionOnlyLoad
317
What method loads an assembly into memory and enables you to execute code?
Assembly.Load
318
What class is used to examine the types within an .exe or .dll file?
System.Reflection.Assembly
319
Name the two ways to get a reference to the Type object
typeof() and .GetType()
320
What is a type?
A class, interface, array, value type, enumeration, parameter, generic type definition, open or closed generic type.
321
The class, porperty or method that contains metadata defined by an attribute is called the...?
Target
322
A lamdba expression containing more than one statement in the body of the expression is referred to as a ...?
statement lambda
323
What is reflection?
Provides lasses that can be used to read metadata or dynamically invoke behavior from a type?
324
Describe probing
The process of looking in the GAC, the host assembly store, the folder of the executing assembly, or the private bin folder of the executing assembly to find an assembly
325
A file, typically a .dll or .exe that composes an assembly is referred to as a ..?
module
326
When loading an assembly using reflection, what context contains the assemblies located inthe path passed into LoadFrom method.
load-from context
327
When loading an assembly during reflection, what context contains the assemblies found by probing
load context
328
Define a lambda expression
Shorthand syntax for an anonymous method that can be associated with a delegate or expression tree.
329
A variable in a class or structure is referred to as a ..?
field
330
Code in a tree-like structure where each node is an expression is referred to as a...?
Expression tree
331
What is an expression lambda?
An expression that contains one statement for the body.
332
What type is a reference to a method?
delegate
333
Define covariance
Enables you to have a method with a more derived return type than the delegates return type
334
Define contravariance
Permits parameter types that are less derived than the delegates parameter types.
335
When loading an assembly using reflection, where does reflection search for the assembly?
in the context
336
Define the CodeDOM
Code Document Object Model Enables the developer to generate code in multiple languages at run time based on single code set.
337
What enables you to associate metadata with assemblies, types, methods, properties...?
attributes
338
A compiled piee of code in a .dll or .exe is referred to as a ?
assembly
339
What method enables you to associate a block of code with a delegate without a method signature?
anonymous methods
340
If during Garbage Collection a program has no path of references that access the object, the object is ?
unreachable
341
Resources that are not under the control of the CLR are known as?
unmanaged resources
342
A base or parent class is also known as?
the superclass
343
The process of deriving a subclass from a base class through inheritance is referred to as ?
subclassing
344
What is a subclass?
A derived class
345
Classes that have the same parent class are referred to?
sibling class
346
A copy of an object where reference fields refer to the same objects as the original is a ..?
shallow clone
347
If the program has a path of references that allow access to the object than it is?
reachable
348
A base, or superclass is known as the?
parent class
349
Because you cannot direct when the GC will call an objects Finalize method, the process is referred to as ?
Nondeterministic finalization
350
Allowing a child class to have more than one parent class?
multiple inheritance (not allowed in C#)
351
Resources that are under the control of the CLR are?
managed resoources
352
Using an interface to require a class to provide certain features much as inheritance does is referred to as ?
Interface inheritance
353
What does it mean to inherit?
A derived class inherits the properties, methods, events and other code from the base class.
354
The process that executes periodically to reclaim memory that is no longer accessible to the program
Garbage Collection (GC)
355
What is Garbage Collection?
The process of running the Garbage Collector to reclaim memory no longer available to the program
356
A queue through with object with finalizers must pass before being destroyed is called the ?
finalization queue
357
What is finalization?
The process of the garbage collection calling the objects Finalize method.
358
What is a destructor?
A method with no return type and the class name preceded by the ~ symbol
359
A class's children, as well as their children are referred to as?
descendant class
360
The creation of one class based on another through inheritance is referred to ?
deriving a class
361
A copy of an object where reference fields refer to new instances of objects?
deep clone
362
A virtual machine that manages C# ( and other .NET) programs is the ?
Common Language Runtime (CLR)
363
A class derived from a parent class is referred to as the ?
child class
364
A class from which another class is derived via inheritance is referred to as the ?
base class
365
A class parent is referred to as an ?
ancestor class
366
What is the purpose of tying the using statement to the Dispose method?
The program automatically calls the Dispose method and limits the object scope to the block.
367
Why does the Dispose method call GC.SuppressFinalize?
Prevents the garbage collector from running objects destructor and keeps the object out of the finalization queue.
368
What resources are freed by a destructor?
unmanaged resources
369
What resources should be freed in a Dispose method?
manage and unmanaged resources
370
Yes or No Can a dispose method be executed more than once?
Yes
371
Yes or No For classes with only unmanaged resources, should IDisposable be implemented?
Yes and it needs to implement a destructor
372
Yes or No For classes with managed resources, should IDisposable be implemented?
Yes, but a destructor is not required
373
Yes or No Do classes with no managed or unmanaged resource require an implementation of IDisposable?
No A destructor is not required
374
What methods are destructors converted to by the compiler?
Finalize
375
Yes or No | Can access modifiers or parameters be defined on a destructor?
No
376
True or False Destructors can be inherited or overloaded?
False
377
How many destructors can be assigned to a class?
No more than one
378
True or False Destructors may be defined in structs and classes
False Destructors are only defined in classes
379
How are objects added to an IEnumerator result
yield return
380
Which interface returns an object used for moving through lists of objects?
IEnumerable
381
What method of ICloneable returns a copy of the object?
Clone
382
What interface provides an equal method to determine if two objects are equal to one another?
IEquatable
383
What interface provides a Compare method to compare two objects to determine their ordering?
IComparer
384
What method from IComparable is provided to determine the order of objects?
CompareTo
385
When code can use either a class instance or interface instance to access the interface, then the interface was implemented how?
implict
386
Define interface inheritance
The act of implementing an interface
387
If a class implements an inteface explicitly, how is the explicit reference acessed?
It must use an interface instance
388
How many classes and interfaces can a class inherit?
``` one class any number of interfaces ```
389
Buy convention, interface names begin with what letter?
I (IEnumerable, etc)
390
True or False If a parent class has constructors, the child class constructor must invoke them directly or indirectly
True
391
True or False At most, a constructor can invoke one base class or one same class constructor.
True
392
Use the this keyword to create a snippet to make a constructor invoke another constructor in the same class
``` public class ClassName { public object PropertyName{get; set;} public object PropertyName2{get; set;} public ClassName(object x) { propertyName = x; } public ClassName(object x, object y) : this( PropertyName(x)) { propertyName2 = y; } ```
393
Use the base keyword to make a constructor to invoke the parent constructor
``` public class Child :Parent { public Child(obj x, obj y) : base(x, y) { // Do something } } ```
394
Does C# support multiple inheritance?
No
395
If a class has unmanaged resources and no managed resources should IDisposable provide a destructor?
Yes Implement IDisposable and provide a destructor
396
If a class has managed resources and no unmanaged resources should IDisposable provide a destructor?
No Implement IDisposabel but provide no destructor
397
If a class implements IDisposable, what three steps should be completed by the Dispose method?
1. Free the managed resources 2. Free unmanaged resources 3. Call GC.SuppressFinalize
398
True or False Destructors are inherited?
False
399
True or False Before destroying an object, the Garbage Collector (GC) calls it's Dispose method?
False The GC calls the Finalize method
400
The IEnumerable and IEnumerator interfaces provide what methods to move through a list of objects?
MoveNext and Reset
401
True or False A class can inherit from at most one class and implement any number of interfaces
True
402
Suppose you want to sort the recipe class by any of the properties; main ingredients, total time or cost per person. Which interface would probably be most useful?
IComparer
403
Suppose you want to make a recipe class to store cooking recipes and you want to sort the recipes by the main ingredient property. Which interface would be most useful?
IComparable
404
Is code reuse a goal of interface design?
No The goals are 1. Simulating multiple inheritance 2. Treating unrelated objects in uniform way 3. Polymorphism
405
Suppose the Houseboa class implements the IHouse interface implicitly and the IBoat interface explicitly. Can the code use Houseboat object to access the IBoat members?
No
406
Suppose you have defined the House and Boat classes and you want to make a HouseBoat class that inherits from House and Boat. Can you inherit from both House and Boat?
No C# classes support single inheritance
407
If the base statement is declared first, can the constructor use a this statement and a base statement?
No
408
Does the use of the base keyword allow a constructor to invoke a different constructor in the same class?
No
409
You are working on a global application with lots of users. The operartion staff requests information on how many user logons per second are occurring. What should you do?
Implement a performance counter using the RateOfCountsPerSecond64 type
410
Users are reporting errors in your application, and you want to configure your application to output more trace data. Which configuration setting should you use?
Switch The switch value determines which trace events should be handled.
411
You are using the TraceSource class to trace data when an order cannot be submitted to the database and you are going to perform a retry. Which TraceEventType should you use?
Error Alerts that something is wrong that needs to be recovered.
412
When experience performance problems, what can you do to isolate and resolve root cause?
Profile the application
413
What classes are used to log and trace messages?
DEBUG and TRACE
414
When should logging and tracing be implemented?
from the beginning of the project
415
You are using custom code generation to insert security checks into your classes. When an exception occurs, you're having trouble finding the correct line in your source code. What should you do?
Use the #line directive with the correct line numbers in your generated code to restoring the original line numbers
416
You are debugging an application for a web shop and are inspecting a lot of Order classes. What can you do to make your debugging easier?
Use the DebuggerDisplayAttribute on the Order class
417
You are ready to deploy your code to a production server. Which configuration do you deploy?
Release configuration
418
What build outputs code that can be deployed to production?
Release build
419
What tools are provided to give extra instructions to the compiler.
compile directives
420
What type of build outputs a nonoptimized version of the code that contains extra instruction to help debugging?
Debug build
421
The compiler can be configured in Visual Studio through use of what tool?
Build configurations
422
You want to deploy an assembly to a shared location on the intranet. Which steps should you take?
Strongly name the assembly Use the codebase configuration element in the applications that use the assembly
423
You are building an assembly that will be used by a couple server applications. You want to move the update process of this assembly as smooth as possible. Which steps should you take?
1. Deploy the assembly to the GAC | 2. Strongly name the assembly
424
You are building a stong-named assembly and you want to reference a regular assembly to resuse some code you built. What steps need to be taken?
You need to sign the other assembly before using it.
425
How are applications bound to the assemblies they were developed with?
by using versioning
426
What is a WinMD assembly?
A special type of assembly used by WinRT to map non-native languages the native WinRT components.
427
Signed assemblies may be placed where?
inside the Global Assembly Cache (GAC)
428
To prevent tampering what may be done to an assembly?
Strongly signed
429
A compiled unit of code that contains metadata is referred to as an ?
assembly
430
You need to send sensitive data to another party and you want to make sure that no other party tampers with the data. Which method do you use?
X509Certificate2.SignHash
431
You need to encrypt a large amount of data. Which algorithm should yoour use?
AESManaged
432
Boba and Alice are using an asymmetric algorithm to exchange data. Which key should they send to the other party to make this possible?
Bob sends Alice his public key | Alice sends Bob her public key
433
What is the method used to verify the authenticity of an author?
Digital Certificates
434
What process is used to retrict the resources and operations an application can access and execute.
CAS
435
What is the purpose of System.Security.SecureString?
Maintains sensitive string data in memory
436
What is hashing?
The process of converting a large amount of data to a smaller hash code
437
What algorithm uses a public and private key that are mathematically linked?
Asymmetric algorithm
438
What algorithm uses the same key to encrypt and decrypt data?
Symmetric algorithm
439
You need to validate an XML file. What do you use?
XML Schema Definition (XSD)
440
You are working on a globalized web application. You need to parse a text field where the user enters an amount of money. What method do you use?
You need to specify the number styles. Currency and culture that the user is using. decimal.TryParse(value, NumberStyles.Currency, UICulture);
441
A user needs to enter a DateTime in a text field. You need to parse value in code. Which method do you use?
DateTime.Parse
442
When receiving JSON and XML files, it is important to validate them using what built-in types.
JavascriptSerializer and XMLSchemas
443
What can be used to match input against a specified pattern or replace specified characters with other values?
regular expressions
444
What functions are used to convert between types?
1. Parse 2. TryParse 3. Convert
445
Where is data integrity managed?
By your application and your data store
446
Why is validating application input important?
To protect your application from mistakes and/or attacks
447
What steps are required to make sure data is not modified while transferred?
1. Calculate the cryptographic hash 2. Send the hash with the data for validation by the receiving party.
448
Name two commonly used hashing algorithms?
SHA256 | SHA512
449
Mapping binary data of a variable length to a fixed size binary data is called?
hashing
450
How are asymmetric private keys secured?
By using certificates or by using Crypto Service Providers containers
451
How are symmetric keys exchanged?
Using asymmetric algorithms
452
Name the four parts of an assembly version
Major Minor Build Revision
453
Name the five parts of a strong name assembly
``` Friendly name Version Culture Public Key Token Processor Architecture ```
454
What is an assembly called that has been digitally signed?
strong named assembly
455
Can more than one version of an assembly be deployed to the GAC?
Yes Several versions of the same assembly can be deployed on the GAC at the same time.
456
What type of assemblies can be deployed to the GAC?
only strong named assemblies
457
What is the GAC?
Global Access Cache A repository to share .NET assemblies
458
A cryptographic protocol used for secure communication ove the Internet, the successor of SSL is called?
Transport Layer Secuirty (TLS)
459
Which method would you call when you use a barrier to mark that a participant reached that point?
SignalAndWait
460
How can you schedule work to be done by a thread from a threadpool?
1. Call the ThreadPool.QueueUserWorkItem | 2. Create a new thread and set property
461
You are a developer at ompany xyz. You have been asked to improve the responsiveness of your WPF application. Which solution best fits the requirement?
BackgroundWorker class
462
Define contravariance
Allow a method to take parameters that are from a superclass of the type expected by the delegate
463
Define covariance
Allows a method to return a value from a subclass of the result expected by a delegate
464
What methods can you use to catch integer overflow exceptions?
1. Use a checked block and a try-catch-finally block | 2. Check the advanced build setting dialogue flow box and use a try-catch-finally block
465
True or False | Can a try-catch-finally block next inside a try-catch-finally block?
Yes
466
True or False A derived class can raise a base class event by using code similar to the following: if( base.EventName != null) bse.EventName(this, args)
False A derived class cannot raise an event defined in an ancestor class.
467
If an object subscribes to an event once and then unsubscribes twice, does the event handler throw an exception when the event is raised.?
No
468
Suppose the card class provides a stopped event that takes as parameters sender and stopped ars objects. Suppose also that the code has already created an appropriate stopped args named args. How do you raise the event?
if( Stopped != null) | Stopped(this, args);
469
How do you evaluate if the variable result holds the value | float.PositiveInfinity
1. result == float.PostiveInfinity 2. float.IsInfinity(result) 3. float.IsPositiveInfinity(result)
470
Which of the following should you not do when building a custom exception class?
Make it implement IDisposable
471
How are events customized?
By adding a custom event accessor and by directly using the underlying delegate type
472
How are events raised?
Events are raised by the declaring class Users of events can only remove or add methods to the invocation list.
473
Define events
A layer of 'syntatic sugar' on top of delegates to easily implement the publish/subscribe pattern.
474
Define lambda expression
Anonymous methods that use the => operator and form a compact way to create inline functions.
475
Define delegates
A type that defines a method signature and cna contain a reference to a method. Delegates can be instantiated passed around and invoked
476
Define Task
A unti fo work
477
Define scheduler
A component of the OS that slices time between threads
478
Define race condition
Occurs when two or more threads access the same data for write operations
479
Define mutual exclusion
The problem of ensuring two threads can't be in the same critical section at the same time.
480
Define multithreading
An operating system or hardware platform that can have several threads operating at the same time.
481
Define fork-join pattern
Process of spawning another thread from the current thread to do work while current thread continues. The current thread waits for spawned thread to finish (using Join)
482
Define EAP
Event-Based Asynchronous Pattern Pattern requires a method to be suffixed with async and provide delegates to signal completion or failure. Not recommended for new development
483
Define | What four conditions lead to a deadlock
1. Mutual exclusion 2. Hold and Wait 3. No preemption 4. Circular wait
484
Define | Deadlock
Two or more threads that attempt to acquire a lock on a resource
485
Define | Atomic Operation
An operation that runs once without interruption by the scheduler
486
Define | APM
``` Asynchronous Pattern Model Pattern split into two parts Begin : Prepares the call and expects immediate return End : Called to return result ``` Used with existing development
487
Define | Asynchrony
Operations run in a non-blocking fashion
488
How do you execute a method as a task?
1. Create a new task, then call the Start method 2. Create and run task (Task.Run()) 3. Create and run task via Task.Factory.StartNew()
489
Which method can be used to cancel an ongoing operation that uses a cancellation token?
Call the cancel method on the CancellationTokenSource used to create the CancellationToken
490
You are processing some data over the network. You use a HasNext and Read method to retrieve the data. You need to run some code on each item. What do you use?
do-while loop
491
You have a lot of checks in your applicaiton for null values. If a value is not null, you want to call a method on it. Which technique would you use?
null-coalescing operator
492
You need to iterate over a collection in which you know the number of items. You need to remove certain items from the collection. Which statement do you use?
for Cannot remove certain items from the collection using foreach
493
You want your type to be able to be converted from string. Which interface should you implement?
IFormattable
494
You want to deploy only the date portion of a DateTime according to the French culture. What method should you use?
dt.ToString("d", new CultureInfo("fr-FR")); d = specifies date fr-FR specifies French language
495
You are parsing a lage piece of text to replace values based on some complex algorithm. Which class should you use?
StringBuilder
496
Name six methods for dealing with strings
``` IndexOf LastIndexOf StartsWith EndsWith SubString ```
497
What is the purpose of StringBuilder?
To enhance the performance of string manipulations
498
Define strings
An immutable reference type
499
Your application is using a lot of memory. Which solution should you address with?
Use a caching element to decide which objects can be freed. You then decie the criteria for freeing memory.
500
Yes or No An object that is implementing IDisposable is passed to your class as an argument. Should you wrap the element in a using statement?
No The calling method should dispose of the object with a using statement
501
You are about to execute a piece of code that is performance sensitive. You are afraid that a garbage collection will occur during the execution of this code. Which method should you call before executing your code?
GC.Collect() Collect will execute a garbage collection, freeing as much memory as possible at that time. It makes further garbage collection less likely to happen.
502
When is a WeakReference used?
To maintain a reference to items that can be garbage collected when necessary.
503
How can yo make sure resources are freed when implementing IDisposable?
By implementing a using statement
504
What is the purpose of IDisposable?
To free unmanaged resources in a deterministic way.
505
What piece of code is executed by the garbage collector when disposing of an object?
Finalizer
506
What comprises memory in a C# program?
Stack (local variables) | Heap (global variables, method/functions)
507
You want to read the value of a private field on a class. Which Binding Flags do you use?
Instance because the filed is non-static NonPuiblic as the filed is declared private ex. BindingFlags.Instance | BindingFlags.NonPublic
508
Memory allocation is managed on the heap by what process?
Garbage Collection (GC)
509
You want to create a delegate that can filter a list of strings on a specific value. What type should you use?
Func, IEnumerable); ``` string = filter IEnumerable = input list IEnumerable = returned filtered list ```
510
You need to create an attribute that can be applied multiple times on a method or parameter. Which syntax should you use?
[AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)]
511
Define expression trees
Expression trees describe a piece of code. Expression trees can be translated to something else (SQL) or compiled and executed.
512
Describe the purpose of the CodeDOM
Used to create a compilation unit at runtime The unit can be compiled or converted to a source file.
513
Define Reflection
The process of inspecting the metadata of a C# application
514
Define Attributes
A type of metadata that can be applied in code and queued at runtime
515
What is stored in a C# assembly?
Code and metadata
516
You want to inherit from an existing class and add some behavior to a method. Name the steps.
Use the virtual keyword on the base method Use the override keyword on the derived method
517
You want to create a type that can be easily sored. Which interface should you implement?
IComparable IComparable enables objects to be compared to each other.
518
Define IComparable
Interface used to sort elements
519
You want to create a hierarchy of types because you have some implementation code you want to store between all types. You also have some method signatures you want to store. What should you use?
An abstract class The abstract class enables you to store both implemented methods and method signatures that a derived class needs to implement.
520
Define IUnknown
Wrapper used to add com objects that are unable to be wrapped by the compiler
521
Define IDisposable
Facilitates working with external unmanaged resources
522
Define IEnumerable
Allows you to iterate over items in the collection
523
Name four primary default interfaces provided by the .NET framework
IComparable IEnumerable IDisposable IUnknown
524
How can you prevent a class from being inherited?
Mark the class as sealed
525
What is the significance of marking a class abstract?
The class cannot be instantiated and can function only as a base class.
526
Name the three C# data structures
Structs Enums Classes
527
Where are value types defined?
Within the .NET Framework
528
How are value types based?
On the number of bits used to store the type
529
How are value types passed to methods?
As a copy
530
Value types are an alias for what object?
System
531
How are value types stored?
Directly
532
How are object values passed in generic methods?
They are passed by reference
533
What does the designator indicate in a generic class?
Serve as a placeholder that will contain the object used
534
What is an advantage of using Generics in .NET?
Generics enable you to create classes that accept the type at creation time.
535
Name on advantage of using named parameters
You can pass the parameters in to the method in any order using parameter names
536
Boxing refers to ?
Converting a value type to a reference type
537
How do enforce encapsulation on the data members of your class?
Create private data members and Public properties
538
When you create an abstract method, how do you use that method in the derived class?
You must override the method in your derived class
539
What is the parameter in this method known as? ``` public void displayAbsoluteValue( int value = 1) { //Do Something } ```
Optional
540
What are two methods with the same name but with different parameters referred to as?
Overloaded methods
541
In the following enumeration, what will be the underlying value of Wed? enum Days{Mon-1, Tues, Wed, Thur, Fri, Sat, Sun}
3
542
What is the correct way to access the firstname property of a struct named Student
var firstName = Student.firstname;
543
True or False | Can structs contain methods?
True
544
Which declaration can assign default value to an int type:
int myInt = new int();
545
True or False double and float types can store values with decimals?
True
546
What is the maximum value you can store in an uint data type?
4,294, 967, 296
547
Define main property abstract methods
Abstract methods do not define and implementation
548
How are overloaded methods defined?
By signature name, types and parameters
549
What purpose do methods serve in classes?
Provide the functionality of the class
550
How many parameters may the default constructor specify?
None Default constructors have no parameters
551
How are constructors named?
With the same name as the class
552
Do constructors specify a return type?
No
553
What is the purpose of the constructor?
To initialize the class
554
What is the purose of fields within a class?
To house data for the class
555
To avoid unwanted modifications, how should fields be marked?
private
556
Name the modifiers that can be used when declaring classes?
``` internal private public protected protected internal ```
557
What is the purpose of class modifiers?
To determine access for classes and class members
558
What is the purpose of member functions within a class?
To describe functionality
559
What is the purpose of member variables within a class?
To describe characteristics or properties
560
Reference types are commonly referred to as?
classes
561
What is the underlying type of enums?
Integers beginning at 0, unless the declaration specified in declaration specifies otherwise
562
How are enumerations formed?
As a list of named constants
563
How are structs passed to methods?
By value
564
Define structs
Lightweight data structures
565
How can derived classes act on base classes marked as virtual?
Derived classes can override virtual methods to add or replace behavior.
566
A class is limited to inheriting how many interfaces?
No limit, unlimited
567
A class is limited to inheriting how many classes?
One, C# support single class inheritance
568
Define interface
An interface specifies the public elements a type myst implement
569
Define inheritance
The process in which a class is derived from another class or from an interface
570
Define generic types
Type parameter used to make code more flexible
571
Name the types in C#
Value Types | Reference Types
572
Define casting
An explicit conversion that requires special syntax
573
Name the conversion options for types
Implicit | Explicit
574
Define boxing
Boxing occurs when a value type is treated as a reference type
575
What keyword can be used to ease the static typing of C# and improve interoperability with other languages
dynamic
576
You have a class that implements two interfaces with the same name. Interface IA should be the default implementation. Interface IB should be used only in special situations. How do your implement these interfaces?
Implement IA implicitly (makes IA default) and IB explicitly.
577
You need to expose some data from a class. The data can be read by other types but can be changed only by derived types. What should you use?
A public property with a protected set modifier.
578
What access modifiers should you use to make sure that a method in a class can only be accessed inside the same assembly by derived types?
The class should be marked internal (only accessed inside project) The members marked as protected (accessed by derived types)
579
Name two uses of explicit interface implementation
1. To hide information | 2. Implement interfaces with duplicate signatures
580
Name the five access modifiers in C# development
``` private public internal protected protected internal ```
581
How is accessability to types and type elements restricted?
Through use of access modifiers
582
Define getters and setters
Property accessors that can run additional code
583
How is data encapsulated in object-oriented design?
Through use of properties
584
Why is encapsulation important in object-oriented design?
Hides internal details and improves usability of type
585
You pass a struct variable into a method as and argument. The method changes the variable; however, when the method returns the method has not changed. What happened?
Passing a value type makes a copy of the data. The original value has not changed.
586
You are creating a generic class that should work only with reference types. Which type constraint should you add?
where T:struct
587
You are creating a new collection type and you want to make sure the elements in it can be easily accessed. What should you add to the type?
Indexer Property
588
Define overriding
Enables you to redefine functionality from a base class in a derived class.
589
How are C# types created?
``` Using ; Constructors Methods Properties Fields Indexers ```
590
Which method will you use to Signal and EventWaitHandle?
set
591
In a multithreaded application how would you increment a variable called counter in a lock free manner?
Interlocked.Increment(ref counter); Interlocked.Add(ref counter, 1);
592
What code is equivalent with ``` lock(syncObject) { // Do something } ```
Monitor.Enter(syncObject); ``` try { } finally { Monitor.Exit(syncObject) } ```
593
Name methods that can be used to start or continue tasks
ContinueWith WhenAll WhenAny
594
Name two methods to create and start a task
1. Task.Run() | 2. Task.Factory.StartNew()
595
An asynchronous unit of work is known as a ?
Task
596
What instrument is used to reduce resource consumption when using threads?
Threadpools
597
Which class abstracts task creation and makes it easier to deal with loops and parallel invokation of methods?
Parallel
598
What class is used to run code in parallel?
The Parallel class
599
What extension is used to run queries in parallel?
PLINQ
600
You are creating a complex query that does not require any particular order and you want to run in parallel. Which method should you use?
AsParallel()
601
You have a lot of items that need to be processed. For each item you need to perform a complex calculation. Which technique should you use?
Parallel.For Best for executing large number of items and processing concurrently.
602
What class is used to create threads explicitly?
Thread class
603
What class is used to allow runtime to handle threads?
Threadpools
604
What is the recommended method to handle multithreaded code?
The Task object
605
You are working on an ASP.NET application that retrieves some data from another web server and then writes the response to the database. Should you use async and await?
Yes This will free server resources to serve other requests waiting for I/O to complete
606
What operators are sued to write asynchronous code more easily?
async and await
607
What is the advantage of a thread?
Improves responsiveness and enables multiple CPU processing.
608
How do u describe a thread?
A virtualized CPU
609
What collection is used to work with data in a multithreaded environment?
Concurrent
610
Define anonymous method
A method without a name. You create a delegate that refers to code the method should contain
611
How are delegates defined?
``` delegate(params) { // Do Something } ``` Ex. Func Square = delegate(float x) { return x * x; };
612
What is the general form of a lambda expression?
() => statement
613
What is the general form of an asynchronous lambda?
``` async (params) => { // Do Something }; ```
614
What is the general form of a statement lambda?
``` () => { // Do Something; return value; }; ```
615
Define subscriber
The class that catches the event
616
Define publisher
An object that raises the event
617
What operators are used to subscribe/unsubscribe to an event?
``` += Subscribes -= Unsubscribe ```
618
Define syntax for declaring an event
AccessModifier event delegate eventName Ex. public delegate void customEventHandler(); public event customEventHandler eventName;
619
Describe the arguments passed to events
First parameter is the object raising the event Second parameter is an object derived from EventArgs
620
Define eventArgs
Arguments relevant to the event
621
Describe form for declaring event arguments
``` class customEventArgs:EventArgs { // instance variables public customEventArgs(instance variables) { // Do someting } } ```
622
Define Microsoft's generic EventHandler delegate
public event EventHandler customEventName
623
Define event inheritance
``` Problem Events can only be raised from within the class that declared it. ``` ``` Solution Provide the base class a protected method that raises the event, then a derived class can call the method ```
624
Define structure of inherited event
``` protected virtual void onMethod(customEventArg) { // Do something } ```
625
Define the statement that subscribes the myButton_Click event handler to catch the myButton controls click event.
myButton.Click += myButton_Click;
626
Suppose the Employee class is derived from the Person class and the Person class defines an AddressChanged event. Which of the following should you do to allow an Employee object to raise this event?
1. Create an OnAddress changed method in the Person class that raises the event. 2. Make the Employee class call OnAddressChanged as needed. 3. Make the code in the Person class that used to raise the event call the OnAddressChanged method instead.
627
Suppose the MovedEventHandler is defined by the statement delegate void MovedEventHandler(); How do you define the Moved event?
public event MovedEventHandler Moved; or public event Action Moved;
628
Define the attributes of statement lambda's
A statement lambda can include more than one statement A statement lambda must use braces If a statement lambda returns a value it must use a return statement
629
In the variable declaration Action processor the variable processor represents?
Methods that take Order as object and return void
630
If an employee class inherits from the Person class, covariance allows you to?
Store a method that returns employee in a delegate that returns a Person
631
If the Employee class inherits from the Person class. Contravariance allows you to?
Store a method that takes Person as a parameter in a delegate that represents methods that take an Employee as parameter
632
Describe delegate variables
1. A struct or class can contain fields that are delegate variables 2. You can make an array or list of delegate variables 3. You can use addition to combine delegate variables and subtraction to remove a method from a series
633
How is a delegate defined?
accessModifier delegate returnType delegateName(params)
634
Name the tools associated with multithreading
TPL (Task Parallel Library) Parallel class PLINQ async and await
635
What actions can be performed with exceptions?
throw catch finally
636
Define events
Events help to create the | publish-subscribe architecture
637
Define lambda expression
Shorthand syntax for creating inline anonymous methods
638
Define delegates
Objects that point to a method and can be used to make methods
639
Name the jump statements
``` break continue goto return throw ```
640
Name the iteration statements
for foreach while do-while
641
Name the decision statements
if switch ? (conditional operator) ?? (null coalescing operator)
642
In a multithreaded environment, it is important to manage synchronization of shared data using which tool?
lock statment
643
You are creating a custom exception called LogonFailedException. Which constructors should you add at minimum?
LogonFailedException(); //default LogonFailedException(string); LogonFailedException(string, exception);
644
What keyword is used to raise an exception?
By using the throw keyword
645
How can you specify code to run whether or not an exception occurs?
with the finally block
646
How are exceptions typically caught in the .NET framework?
using the try..catch block
647
Suppose the variable Note is declared by the statement Action Note. Correctly initialize Note to an expression lambda.
Note = () => MessageBox.Show("Hi");
648
Suppose the variable result is declared by the statement Func result; Correctly initialize result to expression lambda.
result = (float x) => x * x; or result = (x) => x * x;
649
Suppose F is declared by the statement Func F Correctly initialize F to an anonymous method
F = delegate(float x) { return x* x; }
650
In the variable declaration Func processor; The variable processor represents?
A method that takes no parameters and returns and Order object
651
The process of converting a boxed value back to it's original value is known as ?
unboxing
652
How are values displayed at a very high level?
Through standard formatting strings
653
Define narrowing conversion
A data type conversion where the destination type cannot hold all possible values of the source. Requires an explicit conversion
654
What is interoperability
Interoperability enables managed code to use classes provided by unmanaged code not under control of CLR
655
Define the intern pool
A table maintained by the CLR that contains a reference to every unique string used by the program
656
What type of conversion occurs when a program automatically converts a value from one datatype to another
implicit
657
Define immutable
A data type is immutable if its value cannot be changed after creation
658
What do you create to build formats that are not provided by standard formatting strings?
custom formatting strings
659
Describe an explicit conversion
Using a cast or method to explicitly tell a program how to convert a value from one type to another
660
What format item used by string.Format indicates how an argument should be formatted?
The composit format { index[length][:formatString] }
661
What is the CLR?
Common Language Runtime Manages execution of C# and other .NET programs
662
What is the process of converting a value type such as a bool or integer into an object or interface?
boxing
663
Name the most common DateTime formats
``` d: short date D: long data f: full date, short time F:full date, full -time M/m : Month, day t: short time T: long time Y/y: year, month g: general, short time G: general, full time ```
664
Why are standard format strings the preferred method?
They are locale-aware
665
Name two methods that convert values into strings
.ToString() string.Format()
666
What classes provide methods for writing and reading characters and lines with an underlying StringBuilder object?
StringWriter and StringBuilder
667
Your code catches an IOExceptionwhen a file cannot be accessed. You want to give more information to the caller of your code. What do you do?
Throw a new exception with extra information that has the IOException as InnerException
668
You are checking the arguments of your method fro illegal null values. If you encounter a NULL value, which exception do you throw>
ArgumentNullException
669
Define exceptions
Objects that contain data about the exceptions
670
How are errors reported in the .NET framework
via exceptions
671
You have a private method in your class and you want to make invocation of the method possible by certain callers. What do you do?
Use a method that returns a delegate to authorized callers
672
You have declared an event on your class, and you want outside users of your class to raise this event. What do you do?
Add a public method to your class that raises the event
673
You are using a multicast delegate with multiple subscribers. You want to make sure that all subscribers are notified, even if an exception is thrown. What do you do?
Manually raise the event by using GetInvocationList
674
Define Sentinal
A value used to signal the end for execution in a loop
675
Define IEnumerable
A code component in C# that supports iterations
676
Name three generic delegate types defined by the .NET framework
Action Func Predicate
677
Define contravariance
Returns a value from a superclass of the type expected by the delegate
678
Define covariance
Returns a value from a subclass of the result expected by a delegate
679
Name the steps to implementing a delegate
1. Use the delegate keyword to define delegate type 2. Create variables of delegate type 3. Set variables equal to methods that match delegates and return type 4. Invoke the variable
680
How to declare a delegate
accessModifier delegate returnType DelegateName(); ex private delegate int FunctionDelegate(float x);
681
What are best practices for naming delegate types
delegate types should end with the suffix Delegate ex. FunctionDelegate If a delegate is used as a collback, when code finishes suffix with Callback ex FunctionCallback
682
Define Action delegates
A method that returns void and accepts between 0 and 18 parameters
683
Define Func delegates
A method that returns a value and accepts between 0 and 18 parameters
684
Provide example of replacing custom delegate with action delegate
private delegate void FunctionDelegate(param) private FunctionDelegate FunctionParamMethod; replace with: private Action FunctionParamMethod;
685
Provide example of replacing custom delegate with Func delegate
private delegate datatype FunctionDelegate(param) private FunctionDelegate FunctionParamMethod; replace with: private Func FunctionParamMethod;
686
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"); } ```
Yes
687
What kind of result is returned in the condition part of an if statement?
bool
688
You need to move a logical comparison where two values must return true in order for your code to execute the correct statement. What do you do?
&&
689
You want to declare an integer variable called myVar and assign it to the value 0. How can you accomplish this?
int myVar = 0;
690
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?
``` foreach(int numer in arrNumbers) { // Do Something } ```
691
What is the purpose of the break in a switch statement?
It causes the code to exit the switch statement
692
What are the four main repetition structures in C#?
for foreach while do-while
693
How many times will this loop execute? ``` int value = 0; do { Console.WriteLine(value); }while(value > 10); ```
Once
694
A data type conversion where the destination type can hold all values in the source type is known as ?
Widening conversion
695
What encoding is used by the .NET framework
UTF-16, 16 bits per character
696
Define unicode
A standard for encoding characters used by scripts in various locales around the world
697
What pool holds an instance of every unique string?
The intern pool
698
String values do not change, they are referred to as ?
immutable
699
What is a dynamic type
A static type that is not evaluated until runtime
700
When does unboxing occur?
When converting a reference type to a value type
701
How does boxing occur?
When converting a value type to a reference type
702
What class is used to convert data to and from an array of bytes?
System.BitConverter
703
Name the methods in System.Convert
ToBoolean, ToDouble, ToSingle, ToByte, toInt16, ToString, ToChar, ToInt32, ToInt16, ToDateTime, ToInt64, TUInt32, ToDecimal, ToSByte, ToUInt64
704
What class provides methods that convert from one type to another?
System.Convert
705
Name some common styles from System.Globalization.NumberStyles
``` Integer HexNumber Number Float Currency Any ```
706
What enumeration allows Parse and TryParse to understand special symbols?
System.Globalization.NumberStyles
707
What method can be used to parse text and see if ther is an error?
TryParse()
708
How is text parsed into values?
using the Parse() method
709
What is the purpose of the as operator?
To convert an object into a compatible type or NULL if compatibility doesn't exist.
710
What is the purpose of the is operator?
To determine if a variable is compatible with a specific type
711
How are floating point operations checked for overflow or underflow?
By checking the Infinity and/or NegativeInfinity properties
712
How are integer overflows captured?
Using the checked block or Advanced Builds Setting Dialog
713
Yes or No Do explicit conversions require a cast operator?
Yes
714
Yes or No Do implicit conversions require a cast operator?
No
715
Which technique should you use to watch for floating point operations that cause overflow or underflow conditions?
Check the result for the Infinity or NegativeInfinity
716
Which statement can be used to capture integer overflow or underflow errors?
checked
717
Can the string class space method be used to create a string containing 10 spaces?
No
718
Name three common string methods
IndexOf StartsWith Trim (ther are others)
719
If Employee inherits from Person and Manager inherits from Employee then assign a Person to an Employee type.
Person alex = new Employee();
720
The statement object obj=72 is an example of?
boxing
721
What is the best way to store an integer value typed by the user in a variable?
TryParse
722
If i is an int and l is a long then i = (int) l is what ype of conversion?
narrowing conversion
723
Generate a string containing the text "Vend, Vidi, Vici"
String.Format("{0}, {1},{2}", "Vend", "Vidi", "Vici");
724
Assuming total is a decimal variable holding the value 1234.56, which of he following statements display total with currency format $1,234.56?
Console.WriteLine( total.ToString("c"));
725
Name the characteristics of narrowing conversions
The source and destination must be compatible
726
Name the characteristics of widening conversions
Any value of the source type can fit into the destination type The conversion will not result in loss of magnitude but may result in loss of precision An explicit cast is optional
727
Why are properties valuable?
To perform data validations on incoming and outgoing data values
728
What operations can be performed on properties?
read/write read only write only
729
What is the purpose of properties?
To present the public interface to your class
730
In encapsulation, how is data exposed?
Through properties
731
In encapsulation what access modifier is specified for member variables?
private
732
What is the purpose of encapsulation?
Functionality and data are enclosed as part of the class
733
What is another name for data hiding?
encapsulation
734
What enables you to pass arguments to a method in order other than specified in the message signature?
named parameters
735
What allows for giving parameters in a method a name?
named parameters
736
What are the requirements when using optional parameters?
Must exist after required parameters If multiple optional parameters exist and a value is specified for one, all preceding optional parameters must also be supplied values
737
When is a default value used?
If none is passed by caller
738
How are optional parameters defined?
By including a default value
739
Name the type of parameters that enable you to choose the parameters required in a method
optional parameters
740
What type of classes are overridden?
Virtual and abstract methods in base classes
741
What type of method provides the means to change method behavior in a derived class?
overriden methods
742
What is the purpose of extension methods?
To extend existing lasses by adding methods without recompiling
743
Where are extension methods applied?
To your own types or existing types in .NET
744
What is the purpose of overridden methods?
To hide the implementation of a method of the same name in the base class
745
Where are abstract methods defined?
Abstract methods can only be defined in abstract classes
746
You are creating a custom Distance class. You want to ease the conversion from your Distance class to a double. What should you add?
An implicit cast operator
747
What area is used by the .NET compiler to store reference type variables?
heap
748
Variables that store the characteristics data for a class are referred to as?
fields
749
The object that listens for an event to be raised is?
The event subscriber
750
The object that raises the event for the listener or subscriber is the ?
event publisher
751
A distinct type consisting of a set of named constants is known as an ?
enumeration
752
The hiding of details around the implementation of an object so there are no external dependencies on the particular implementation?
encapsulation
753
Components in code that are used to store data within a program are referred to as?
data structures
754
What class methods are executed when an object of a given type is created?
constructors
755
What are coding components that enable you to create custom types to group together characteristics, mehtods and events
classes
756
What is used to encapsulate data and functionality into one unit of code
class files
757
What methods are used to access hidden number variables?
accessor methods
758
When can an abstract modifier be used?
With classes, methods, properties, indexers and events
759
When is an abstract modifier used?
To indicate that a class is intended to be only a base class of other classes
760
What technique is used to define methods without specifying the types for parameters at definition stage?
generic types
761
What is the purpose of the generic type?
Enables type-safe coding Increase performance due to reduction in conversions, boxing/unboxing.
762
What types are used as a placeholder at define stage that is replaced by type during instantiation?
generic types
763
How are indexed properties accessed?
Using an index in the same manner as arrays
764
What properties allow array like access to group of items?
idexers (indexed properties)
765
What are instance fields?
fields related to a specific instance. Values are not shared among objects of the same class.
766
You are using an ArrayList as a collection for a list of points, which are a custom struct. You are experiencing performance problems when working with a large amount of points. What do yo have to do?
Use a generic collection instead of ArrayList
767
Define properties
Members that provide a flexible mechanixm to read, write or compute the values of private fields.
768
When is the override access method used?
To extend or modify the abstract or virtual implementation of an inherited method, property, indexer or event.
769
What is the purpose of the modifier?
Modify declarations of types and type members
770
What is used to provide functionality for a class?
method
771
What is a memory address?
An addressable location in computer memory used to store and retrieve values
772
You want to determine whether the value of an object reference is derived from a particular type. Which C# feature can you use?
An as operator An is operator
773
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?
NumberStyles.Currency
774
An area of memory used by the .NET compiler to store value types during program execution is known as the?
Stack
775
Methods with identical names for procedures that operate on different data types are referred to as ?
overloaded methods
776
The unique identifying components of a method, such as return type, name and parameter is known as it's?
signature
777
class files or other objects represented as references to the actual data (memory address) are referred to as ?
reference types
778
In entity framework, which class is responsible for maintaining the bridge between a database engine and C# code?
DbContext
779
Which method is used to return a specific number of objects from a quuery result?
Take()
780
Which of collection types is used to retrieve data in a Last-In, Last-Out (LIFO) way?
Stack
781
What keyworkd is used to filter a query?
Where()
782
Which extension method is used to join two queries?
join()
783
Suppose you're writing a method that retrieves the data from an MS Access 2013 database. The method must meet the following requirements; 1. Be read-only 2. Be able to use the data before the entire data set is retrieved 3. Minimize the amount of system overhead and amount of memory usage What type of object should be used in the method?
Because MS Access OleDbDataReader
784
Suppose you have the following code segment: 01. ArrayList arrays = new ArrayList(); 02. int i = 10 ; 03. int j; 04. arrays.Add(i); 05. j = arrays[0]; You need to resolve the error that occurs at line 05 ("Cannot implicitly convert type object to int"). You need to ensure that the error gets removed. Which code should you replace in line 05?
j = (int)arrays[0];
785
``` Suppose you have the following code snippet: 01. class Person 02. { 03. public int ID { get; set; } 04. public string Name { get; set; } 05. public int Age { get; set; } 06. } 07. Dictionary people = new Dictionary 08. { 09. {21, new Person {ID = 1, Name="Ali", Age = 22 } }, 10. {22, new Person {ID = 2, Name="Sundus", Age = 21 } }, 11. {23, new Person {ID = 3, Name="Asad", Age = 22 } }, 12. {24, new Person {ID = 5, Name="Naveed", Age = 21 } }, 13. }; 14. 15. people.Add(24, new Person { ID = 6, Name = "Malik", Age = 10 }); ``` The application fails at line 15 with the following error message: "An item with the same key has already been added." You need to resolve the error. Which code segment should you insert at line 14? A) if(!people.ContainsKey(24)) B) foreach (Person person in people.Values.Where(t=>t.ID !=24)) C) foreach (KeyValuePair key in people.Where(t=>t.Key != 24)) D) foreach (int key in people.Keys.Where(k=>k!=24))
A) if(!people.ContainsKey(24))
786
``` You’re creating an application that counts the number of times a specific word appears in a text file. See the following code snippet: 01. class Demo 02. { 03. ConcurrentDictionary words = 04. new ConcurrentDictionary(); 05. public Action ProcessDir() 06. { 07. Action act = (dirInfo => 08. { 09. var files = dirInfo.GetFiles("*.cs").AsParallel(); 10. files.ForAll( 11. fileinfo => 12. { 13. var content = File.ReadAllText(fileinfo.FullName); 14. var sb = new StringBuilder(); 15. foreach (var item in content) 16. { 17. sb.Append(char.IsLetter(item) ? 18. item.ToString().ToLowerInvariant() : " "); 19. } 20. var wordlist= sb.ToString().Split(new[] { ' ' }, 21. StringSplitOptions.RemoveEmptyEntries); 22. foreach (var word in wordlist) 23. { 24. 25. } 26. }); 27. var dir = dirInfo.GetDirectories() 28. .AsParallel(); 29. dir.ForAll(ProcessDir()); 30. }); 31. return act; 32. } 33. } ``` You need to populate a words object with the list of words and the number of occurrences of each word, and also ensure that the updates to the ConcurrentDictionary object can happen in parallel. Which code segment should you insert at line 24? ``` A) words.AddOrUpdate(word, 1, (s, n) => n + 1); B) int value; if(words.TryGetValue(word, out value)) { words[word] = value++; } else { words[word] = 1; } ```
A) words.AddOrUpdate(word, 1, (s, n) => n + 1);
787
You have a List object that is generated by executing the following code: List subjects = new List() { "English","Computer","Maths","Physics" }; You have a method that contains the following code: 01. bool GetSameSubjs(List subj, string searchSubj) 02. { 03. var findSubj = subj.Exists((delegate (string subjName) 04. { 05. return subjName.Equals(searchSubj); 06. } 07. )); 08. return findSubj; 09. } You need to alter the method to use a lambda statement. How should you rewrite lines 03 through 06 of the method? A) var findSubj = subj.First(x => x == searchSubj); B) var findSubj = subj.Where(x => x == searchSubj); C) var findSubj = subj.Exists(x => x.Equals(searchSubj)); D) var findSubj = subj.Where(x => x.Equals(searchSubj));
C) var findSubj = subj.Exists(x => x.Equals(searchSubj));
788
``` Which of the following two interfaces should you use to iterate over a collection and release the unmanaged resources. A) IEquatable B) IEnumerable C) IDisposable D) IComparable ```
B) IEnumerable | C) IDisposable
789
You are creating an application that will parse a large amount of text. You need to parse the text into separate lines and minimize memory use while processing data. Which object type should you use? A) DataContractSerializer B) StringBuilder C) StringReader D) JsonSerializer
B) StringBuilder
790
You need to store the values in a collection. 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 ```
B) Queue
791
You need to choose a collection type which internally stores a key and a value for each collection item, provides objects to iterators in ascending order based on the key, and ensures that items are accessible by a zero-based index or by key. Which collection type should you use? A) SortedList B) Queue C) Array D) HashTable
A) SortedList
792
You are creating an application that uses a class named Person. The class is decorated with the DataContractAttribute attribute. The application includes the following code snippet: 01. MemoryStream WritePerson(Person person) 02. { 03. var ms = new MemoryStream(); 04. var binary = XmlDictionaryWriter.CreateBinary(ms); 05. var ser = new DataContractSerializer(typeof(Person)); 06. ser.WriteObject(binary, person); 07. 08. return ms; 09. } You need to ensure that the entire Person object is serialized to the memory stream object. Which code segment should you insert at line 07? A) binary.WriteEndDocument(); B) binary.WriteEndDocumentAsync(); C) binary.WriteEndElementAsync(); D) binary.Flush();
A) binary.WriteEndDocument();
793
``` You are developing a class named Person. See the following code snippet: 01. class People 02. { 03. Dictionary people = new Dictionary(); 04. public void Add(string name, int age) 05. { 06. people.Add(name, age); 07. } 08. 09. } It has the following unit test: public void UnitTest1() { People people = new People(); people.Add("Ali", 22); people.Add("Sundus", 21); int expectedAge = 21; int actualAge = people["Sundus"]; Assert.AreEqual(expectedAge, actualAge); } You need to ensure the unit test will pass. What code snippet you should insert at line 08? A) public Dictionary People { get { return people; } } B) public int this[string name] { get { return people[name]; } } C) public Dictionary People = new Dictionary(); D) public int salary(string name) { return people[name]; } ```
``` B) public int this[string name] { get { return people[name]; } } ```
794
You’re creating an application that converts data into multiple output formats; it includes the following code snippets. 01. class TabDelimitedFormatter : IFormatter 02. { 03. readonly Func suffix = 04. col => col % 2 == 0 ? '\n' : '\t'; 05. public string Output(IEnumerator iterator, int size) 06. { 07. 08. } 09. } 10. interface IFormatter 11. { 12. string Output(IEnumerator iterator, int size); 13. } You need to minimize the completion time of the GetOutput() method. Which code segment should you insert at line 07? A) string output = null; for(int i = 1; iterator.MoveNext(); i++) { output = string.Concat(output, iterator.Current, suffix(i)); } B) var output = new StringBuilder(); for(int i = 1; iterator.MoveNext(); i++) { output.Append(iterator.Current); output.Append(suffix(i)); } C) string output = null; for(int i = 1; iterator.MoveNext(); i++) { output = output + iterator.Current + suffix(i); } D) string output = null; for(int i = 1; iterator.MoveNext(); i++) { output += iterator.Current + suffix(i); }
``` B) var output = new StringBuilder(); for(int i = 1; iterator.MoveNext(); i++) { output.Append(iterator.Current); output.Append(suffix(i)); } ```
795
Suppose you’re writing a method named ReadFile that reads data from a file. You must ensure that the ReadFile method meets the following requirements: 1. It must not make changes to the data file. 2. It must allow other processes to access the data file. It must not throw an exception if the application attempts to open a data file that does not exist. Which code segment should you use? A) var fs = File.Open(Filename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite); B) var fs = File.Open(Filename, FileMode.Open, FileAccess.Read, FileShare. ReadWrite); C) var fs = File.Open(Filename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write); D) var fs = File.ReadAllLines(Filename); E) var fs = File.ReadAllBytes(Filename);
``` A) var fs = File.Open(Filename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite); ```
796
You’re using ADO.NET Entity Framework to retrieve data from a database in MS SQL Server. Suppose you have the following code snippet: 01. public DataTime? OrderDate; 02. IQueryable GetOrderByYear(int year) 03. { 04. using (var context = new NortwindEntities()) 05. { 06. var orders = from order in context.Orders; 07. 08. select order; 09. return orders.ToList().AsQueryable(); 10. } 11. } You need to ensure the following requirements: 1. Return only orders that have an OrderDate value other than null. 2. Return only orders that were placed in the year specified in the OrderDate property or in a later year. Which code segment should you insert at line 07? A) Where order.OrderDate.Value != null && order.OrderDate.Value.Year > = year B) Where order.OrderDate.Value = = null && order.OrderDate.Value.Year = = year C) Where order.OrderDate.HasValue && order.OrderDate.Value.Year = = year D) Where order.OrderDate.Value.Year = = year
A) Where order.OrderDate.Value != null && order.OrderDate.Value.Year > = year
797
An application has the following code: 01. class Person 02. { 03. public string Name { get; set; } 04. public int Age { get; set; } 05. } 06. static IEnumerable GetPersons(string sqlConnectionString) 07. { 08. var people = new List(); 09. SqlConnection sqlConnection = new SqlConnection(sqlConnectionString); 10. using (sqlConnection) 11. { 12. SqlCommand sqlCommand = new SqlCommand("Select Name, Age From 13. Persons", sqlConnection); 14. 15. using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader()) 16. { 17. 18. { 19. Person person = new Person(); 20. person.Name = (string)sqlDataReader["Name"]; 21. person.Age = (int)sqlDataReader["Age"]; 22. 23. people.Add(person); 24. } 25. } 26. } 27. return people; 28. } The GetPersons() method must meet the following requirements: 1. Connect to a Microsoft SQL Server database. 2. Create Animal objects and populate them with data from the database. Which two actions should you perform? A) Insert the following code segment at line 17: while(sqlDataReader.NextResult()) B) Insert the following code segment at line 14: sqlConnection.Open(); C) Insert the following code segment at line 14: sqlConnection.BeginTransaction(); D) Insert the following code segment at line 17: while(sqlDataReader.Read()) E) Insert the following code segment at line 17: while(sqlDataReader.GetValues())
B) Insert the following code segment at line 14: sqlConnection.Open(); C) Insert the following code segment at line 14: sqlConnection.BeginTransaction();
798
Suppose you have a collection of integer values. You define an integer variable named IntegerToRemove and assign a value to it. You declare an array named filteredIntegers. You must to do the following things. Remove duplicate integers from the integer array. Sort the array in order from the highest value to the lowest value. Remove the integer value stored in the integerToRemove variable from the integers array. Which LINQ query would you need to create to meet the requirements? A) int[] filteredIntegers = integers.Where(value => value != integerToRemove).OrderBy(x => x).ToArray(); B) int[] filteredIntegers = integers.Where(value => value != integerToRemove).OrderByDescending(x => x).ToArray(); C) int[] filteredIntegers = integers.Distinct().Where(value => value != integerToRemove).OrderByDescending(x => x).ToArray(); D) int[] filteredIntegers = integers.Distinct() .OrderByDescending(x => x).ToArray();
C) int[] filteredIntegers = integers.Distinct().Where(value => value != integerToRemove).OrderByDescending(x => x).ToArray();
799
Suppose you’re creating an application that includes the following code, which retrieves JSON data. You need to ensure that the code validates the JSON. 01. bool ValidateJSON(string json, Dictionary result) 02. { 03. 04. try 05. { 06. result = serializer.Deserializer>(json); 07. return true; 08. } 09. catch 10. { 11. return false; 12. } 13. } ``` Which code should you insert at line 03? A) var serializer = new DataContractSerializer(); B) DataContractSerializer serializer = new DataContractSerializer(); C) var serializer = new XmlSerializer(); D) var serializer = new JavaScriptSerializer(); ```
D) var serializer = new JavaScriptSerializer();
800
``` Suppose you have a List people = new List(); You need to create an extension method that will return the correct number of Person objects from the people list that can be displayed on each page and each page has a uniform page size. Which code snippet should you use? A) Public static IEnumerable Page(IEnumerable source, int page, int pagesize) { return source.Take((pagesize - 1) * page).Skip(pagesize); } B) Public static IEnumerable Page(this IEnumerable source, int page, int pagesize) { return source.Skip((page - 1) * pagesize).Take(pagesize); } C) static IEnumerable Page(IEnumerable source, int page, int pagesize) { return source.Skip((pagesize - 1) * page).Take(pagesize); } D) Public static IEnumerable Page(this IEnumerable source, int page, int pagesize) { return source.Take((page - 1) * pagesize).Skip(pagesize); } ```
B) Public static IEnumerable Page(this IEnumerable source, int page, int pagesize) { return source.Skip((page - 1) * pagesize).Take(pagesize); }
801
``` Suppose you’re developing an application that needs to read the data from a file and then release the file resources. Which code snippet should you use? A) string data; using (StreamReader readfile = new StreamReader("data.txt")) { while ((data = readfile.ReadLine()) != null) { Console.WriteLine(data); } } B) string data; StreamReader readfile = null; using ( readfile = new StreamReader("data.txt")) { while ((data = readfile.ReadLine()) != null) { Console.WriteLine(data); } } C) string data; StreamReader readfile = new StreamReader("data.txt"); while ((data = readfile.ReadLine()) != null) { Console.WriteLine(data); } D) string data; StreamReader readfile = null; try { readfile = new StreamReader("data.txt"); while ((data = readfile.ReadLine()) != null) { Console.WriteLine(data); } readfile.Close(); readfile.Dispose(); } finally { } ```
``` A) string data; using (StreamReader readfile = new StreamReader("data.txt")) { while ((data = readfile.ReadLine()) != null) { Console.WriteLine(data); } } ```
802
``` Suppose you are developing an application that includes the following code: List list = new List { 80, 75, 60, 55, 75 }; You have to retrieve all the numbers that are greater than 60 from a list. Which code should you use? A) var result = from i in list where i > 60 select i; B) var result = list.Take(60); C) var result = list.First(i => i > 80); D) var result = list.Any(i => i > 80); ```
A) var result = from i in list where i > 60 select i;
803
``` You want to configure your application to output more trace data. What would you use for the configuration setting? A) Listener B) Filter C) Switch D) Trace ```
C) Switch
804
You are developing an assembly that will be used by server applications. You want to make the update process of this assembly as smooth as possible. What steps would you take? A) Create WinMD Assembly B) Deploy Assembly to GAC C) Sign the assembly with the storing name D) Delay sign the assembly
B) Deploy Assembly to GAC
805
``` You need to send your data to a receiver and want no one to tamper with your data. What would you use? A) X509Certificate2.SignHash B) RSACryptoServiceProvider.Enrypt C) UnicodeEncoding.GetBytes D) Marshal.ZeroFreeBSTR ```
A) X509Certificate2.SignHash | C) UnicodeEncoding.GetBytes
806
``` You need to validate an XML file. What would you use? A) XSD B) RegEx C) StringBuilder D) JavaScriptSerializer ```
A) XSD
807
``` Which method is easiest to find the problem if you have no idea what it is? A) Using Profiler B) Profiling by Hand C) Using Performance Counter D) Debugging ```
A) Using Profiler
808
``` To build a project you need a PDB file of: A) Previous build version B) Any build version C) Current Solution File D) Same build version ```
D) Same build version
809
``` Which class should preferably be used for tracing in Release Mode? A) Debug B) Trace C) TraceSource D) All of the above ```
C) TraceSource
810
Which bindingflags are useful for getting the private data instance? A) BindingFlags.NonPublic | BindingFlags.Instance B) BindingFlags.Private | BindingFlags.Instance C) BindingFlags.NonPrivate | BindingFlags.NonStatic D) BindingFlags.Private | BindingFlags.NonStatic
A) BindingFlags.NonPublic | BindingFlags.Instance
811
``` Which of the following methods is used for getting the information of a current assembly? A) Assembly. GetExecutingAssembly(); B) Assembly.GetExecutedAssembly(); C) Assembly.GetCurrentAssembly(); D) Assembly.ExecutingAssembly(); ```
A) Assembly. GetExecutingAssembly();
812
``` Which of the following commands is required to create a strong name key? A) sn -k {assembly_name}.snk B) sn k {assembly_name}.snk C) gacutil -i {assembly_name}.snk D) gacutil i {assembly_name}.snk ```
A) sn -k {assembly_name}.snk
813
Salt Hashing is done by: A) Merging data with a random value and performing Cryptography B) Merging data with a random value and performing Cryptanalysis C) Merging data with a random value and performing Encryption D) Merging data with a random value and performing Hashing
D) Merging data with a random value and performing Hashing
814
You are developing an application which transmits a large amount of data. You need to ensure the data integrity. Which algorithm should you use? A) RSA B) HMACSHA256 C) Aes D) RNGCryptoServiceProvider
B) HMACSHA256
815
``` The application needs to encrypt highly sensitive data. Which algorithm should you use? A) DES B) Aes C) TripleDES D) RC2 ```
B) Aes
816
``` How would you throw an exception to preserve stack-trace information? A) throw; B) throw new Exception(); C) throw e; D) return new Exception(); ```
A) throw;
817
``` You need to validate a string which has numbers in 333-456 format. Which pattern should you choose? A) @"\d\d-\d\d" B) @"\n{3}-\n{3}" C) @"[0-9]+-[0-9]" D) @"\d{3}-\d{3}" ```
D) @"\d{3}-\d{3}"
818
You are required to install an assembly in GAC. Which action should you take? A) Use the Assembly Registration tool (regasm.exe) B) Use the strong name tool (sn.exe) C) User Microsoft register server (regsvr32.exe) D) Use the Global Assembly Cache tool (gacutil.exe) E) Use Windows installer 2.0
D) Use the Global Assembly Cache tool (gacutil.exe) | E) Use Windows installer 2.0
819
You have the following code snippet: If(! PerformanceCounterCategory.Exists(“CounterExample”)) { Var counters=new CounterCreationDataCollection(); Var counter1=new CounterCreationData { CounterName=”Counter1”, CounterType=PerformanceCounterType.SampleFraction }; Var counter2=new CounterCreationData { CounterName=”Counter2” }; Counters.Add(counter1); Counters.Add(counter2); PerformanceCounterCategory.Create(“CounterExample”,””,PerformanceCounterCategoryType. MultiInstance,counters); } You need to ensure that counter1 is available for performance monitor. Which code segment should you use? A) CounterType=PerformanceCounterType.RawBase B) CounterType=PerformanceCounterType.AverageBase C) CounterType=PerformanceCounterType.SampleBase D) CounterType=PerformanceCounterType.CounterMultiBase
C) CounterType=PerformanceCounterType.SampleBase
820
``` You have to class ExceptionLogger and its method LogExecption, which logs the exception. You need to log all exceptions that occur and rethrow the original, including the entire exception stack. Which code segment should you use for the above requirements? A) Catch(Exception ex) { ExceptionLogger.LogException(ex); throw; } B) Catch(Exception ex) { ExceptionLogger.LogException(ex); throw ex; } ``` ``` C) Catch(Exception) { ExceptionLogger.LogException(); throw; } D) Catch(Exception ) { ExceptionLogger.LogException(ex); throw ex; } ```
``` A) Catch(Exception ex) { ExceptionLogger.LogException(ex); throw; } ```
821
You are required to create an event source named mySource and a custom log named myLog on the server. You need to write the “Hello” information event to the custom log. Which code segment should you use? A) EventLog Log=new EventLog(){Source=”mySource”}; Log.WriteEntry(“Hello”,EventLogEntryType.Information); B) EventLog Log=new EventLog(){Source=”myLog”}; Log.WriteEntry(“Hello”,EventLogEntryType.Information); C) EventLog Log=new EventLog(){Source=”System”}; Log.WriteEntry(“Hello”,EventLogEntryType.Information); D) EventLog Log=new EventLog(){Source=”Application”}; Log.WriteEntry(“Hello”,EventLogEntryType.Information);
``` A) EventLog Log=new EventLog(){Source=”mySource”}; Log.WriteEntry(“Hello”,EventLogEntryType.Information); ```
822
You are required to create a program with the following requirements: In Debug Mode, console output must display Entering Release Mode. In Release Mode, console output must display Entering Debug Mode. Which code segment should you use? A) if DEBUG.DEFINED Console.WriteLine(“Entering Release Mode”); else Console.WriteLine(“Entering Debug Mode”); B) if RELEASE.DEFINED Console.WriteLine(“Entering Debug Mode”); else Console.WriteLine(“Entering Release Mode”); C) #if DEBUG Console.WriteLine(“Entering Release Mode”); #elif RELEASE Console.WriteLine(“Entering Debug Mode”); D) #if DEBUG Console.WriteLine(“Entering Debug Mode”); #elif RELEASE Console.WriteLine(“Entering Release Mode”);
C) #if DEBUG Console.WriteLine(“Entering Release Mode”); #elif RELEASE Console.WriteLine(“Entering Debug Mode”);
823
You are creating a library (.dll file) for your project. You need to make it a strongly typed assembly. What should you do? A) use the csc.exe/target:Library option when building the application B) use the AL.exe command line-tool C) use the aspnet_regiis.exe command line-tool D) use the EdmGen.exe command line-tool
B) use the AL.exe command line-tool
824
You are required to create a class “Load” with the following requirements: Include a member that represents the rate of a Loan instance. Allow an external code to assign a value to a rate member. Restrict the range of values that can be assigned to the rate member. To meet these requirements, how would you implement the rate member? A) public static property B) public property C) public static field D) protected field
B) public property
825
``` You are required to develop a method which can be called by a varying number of parameters. The method is called: A) Method Overriding B) Method Overloading C) Abstract Method D) Virtual Method ```
B) Method Overloading
826
``` You are working on an application where you need to encrypt highly sensitive data. Which algorithm should you use? A) DES B) Aes C) TripleDES D) RC2 ```
B) Aes
827
``` You need to create a unique identity for your application assembly. Which two attributes should you include for this purpose? A) AssemblyTitleAttribute B) AssemblyCultureAttribute C) AssemblyVersionAttribute D) AssemblyKeyNameAttribute E) AssemblyFileVersion ```
B) AssemblyCultureAttribute | C) AssemblyVersionAttribute
828
``` Which statement is used to remove the unnecessary resources automatically? A) using B) switch C) Uncheck D) Check ```
A) using
829
``` Which class is necessary to inherit while creating a custom attribute? A) Exception B) Attribute C) Serializable D) IEnumerable ```
B) Attribute
830
``` Which of the following interfaces is used to manage an unmanaged resource? A) IUnkown B) IEnumerable C) IComparable D) IDisposable ```
D) IDisposable
831
``` Which of the following interfaces is necessary to implement for creating a custom collection in C#? A) IUnkown B) IEnumerable C) IComparable D) IDisposable ```
B) IEnumerable
832
``` How would you parse a type to another in a way that it doesn’t generate an exception in a wrong conversion? A) as B) is C) out D) in ```
A) as
833
``` Which keyword is used to check or compare one type to another? A) as B) is C) out D) in ```
B) is
834
``` How should you create an extension method of an integer? A) static class ExtensionClass { public static void ExtensionMethod(this int i) { //do code } } B) static class ExtensionClass { public static void ExtensionMethod(int i) { //do code } } ``` ``` C) class ExtensionClass { public static void ExtensionMethod(this int i) { //do code } } D) static class ExtensionClass { public void ExtensionMethod(this int i) { //do code } } ```
``` A) static class ExtensionClass { public static void ExtensionMethod(this int i) { //do code } } ```
835
``` What should you use to encapsulate an array object? A) Indexer B) Property C) Event D) Private array ```
A) Indexer
836
``` Which of the following keywords is used for a dynamic variable? A) var B) dynamic C) const D) static ```
B) dynamic
837
``` Which of the following methods of assembly is used to get all types? A) GetTypes() B) GetType() C) ToTypeList() D) Types() ```
A) GetTypes()
838
How would you make sure the garbage collector does not release the object’s resources until the process completes? Which garbage collector method should you use? A) WaitForFullGCComplete() B) SuppressFinalize() C) collect() D) RemoveMemoryPressure()
B) SuppressFinalize()
839
``` You are developing an application that includes the following code segment: 01. class A { } 02. class B : A { } 03. class C 04. { 05. void Demo(object obj) { Console.WriteLine("Demo(obj)"); } 06. void Demo(C c) { Console.WriteLine("Demo(C)");} 07. void Demo(A a) { Console.WriteLine("Demo(A)");} 08. void Demo(B b) { Console.WriteLine("Demo(B)");} 09. 10. void Start() 11. { 12. object o = new B(); 13. Demo(o); 14. } 15. } You need to ensure that the Demo(B b) method runs. With which code segment should you replace line 13? A) Demo((B)o); B) Demo(new B(o)); C) Demo(o is B); D) Demo((A)o); ```
A) Demo((B)o);
840
How would you ensure that the class library assembly is strongly named? What should you do? A) Use the gacutil.exe command-line tool. B) Use the xsd.exe command-line tool. C) Use the aspnet_regiis.exe command-line tool. D) Use assembly attributes.
D) Use assembly attributes.
841
Suppose you are developing an application that includes an object that performs a long-running process. You need to ensure that the garbage collector does not release the object’s resources until the process completes. Which garbage collector method should you use? A) WaitForFullGCComplete() B) WaitForFullGCApproach() C) KeepAlive() D) WaitForPendingFinalizers()
C) KeepAlive()
842
``` You need to convert a date value entered in string format and you need to parse it into DateTime and convert it to Coordinated Universal Time (UTC). The code must not cause an exception to be thrown. Which code segment should you use? A) string strDate = ""; bool ValidDate = DateTime.TryParse(strDate, CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal, out ValidatedDate); B) string strDate = ""; bool ValidDate = DateTime.TryParse(strDate, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out ValidatedDate); C) bool validDate = true; try { ValidatedDate = DateTime.Parse(strDate); } catch { validDate = false; } ```
A) string strDate = ""; bool ValidDate = DateTime.TryParse(strDate, CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal, out ValidatedDate);
843
``` How would you convert the following values? 01. float ft; 02. object o = ft; 03. 04. Console.WriteLine(i); You need to ensure that the application does not throw exceptions on invalid conversions. Which code segment should you insert at line 03? A) int i = (int)(float)o; B) int i = (int)o; C) int i = o; D) int i = (int)(double)o; ```
A) int i = (int)(float)o;
844
You are creating a class named Person. The class has a string property named FirstName. 01. class Person 02. { 03. public string FirstName 04. { 05. get; 06. set; 07. } 08. } The FirstName property value must be accessed and modified only by code within the Person class or within a class derived from the Person class. Which two actions should you perform? A) Replace line 05 with the protected get; B) Replace line 06 with the private set; C) Replace line 03 with the public string EmployeeType D) Replace line 05 with the private get; E) Replace line 03 with the protected string EmployeeType F) Replace line 06 with the protected set;
B) Replace line 06 with the private set; | E) Replace line 03 with the protected string
845
``` Suppose you’re creating an application that concatenates “1” value with a string for a million times. Which of the following codes would you use that minimize the completion time and concatenates the string for the millionth time? A) string str = ""; for (int i = 0; i < 1000000; i++) { str = string.Concat(str, "1"); } return str; B) var str = new StringBuilder(); for (int i = 0; i < 1000000; i++) { str.Append("1"); } return str.ToString(); C) var str = null; for (int i = 0; i < 1000000; i++) { str = str + "1"; } return str.ToString(); D) var str = null; for (int i = 0; i < 1000000; i++) { str += "1"; } return str.ToString(); ```
``` B) var str = new StringBuilder(); for (int i = 0; i < 1000000; i++) { str.Append("1"); } return str.ToString(); ```
846
Suppose you are developing an application that includes classes named Car and Vehicle and an interface named IVehicle. The Car class must meet the following requirements: It must either inherit from the Vehicle class or implement the IVehicle interface. It must be inheritable by other classes in the application. You need to ensure that the Car class meets the requirements. Which two code segments can you use to achieve this goal? A) sealed class Car : Vehicle { ... } B) abstract class Car: Vehicle { ... } ``` C) sealed class Car : IVehicle { ... } D) abstract class Car : IVehicle { } ```
``` B) abstract class Car: Vehicle { ... } ``` ``` D) abstract class Car : IVehicle { } ```
847
Suppose you are creating an application that manages the information of persons. The application includes a class named Person and a method named Save. The Save() method must be strongly typed. It must allow only types inherited from the Person 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(T target) where T: new(), Person { ... } B) public static void Save(T target) where T: Person { ... } C) public static void Save(T target) where T: Person, new() { ... } D) public static void Save(Person person) { ... }
``` C) public static void Save(T target) where T: Person, new() { ... } ```
848
``` Suppose you are developing an application that uses the following C# code: 01. public interface IPerson 02. { 03. string Name { get; set; } 04. } 05. 06. void Demo(object obj) 07. { 08. 09. if(person != null) 10. { 11. System.Console.WriteLine(person.Name); 12. } 13. } The Demo() method must not throw any exceptions when converting the obj object to the IPerson interface or when accessing the Data property. You need to meet the requirements. Which code segment should you insert at line 08? A) var person = (IPerson)obj; B) dynamic person = obj; C) var person = obj is IPerson; D) var person = obj as IPerson; ```
D) var person = obj as IPerson;
849
``` You are developing an application. The application converts a Person object to a string by using a method named WriteObject. The WriteObject() method accepts two parameters: a Person object and an XmlObjectSerializer object. The application includes the following code: 01. public enum Gender 02. { 03. Male, 04. Female, 05. Others 06. } 07. [DataContract] 08. public class Person 09. { 10. [DataMember] Chapter 16 ■ Practice Exam Questions 434 11. public string Name { get; set; } 12. [DataMember] 13. public Gender Gender { get; set; } 14. } 15. void Demo() 16. { 17. var person = new Person { Name = "Ali", Gender = Gender.Male }; 18. Console.WriteLine(WriteObject(person, 19. 20. )); 21. } You need to serialize the Person object as a JSON object. Which code segment should you insert at line 19? A) new DataContractSerializer(typeof(Person)) B) new XmlSerializer(typeof(Person)) C) new NetDataContractSenalizer() D) new DataContractJsonSerializer(typeof(Person)) ```
D) new DataContractJsonSerializer(typeof(Person))
850
You’re creating an application that receives a JSON data in the following format: { "Name" : "Ali", "Age" : "22", "Languages": ["Urdu", "English"] } The application includes the following code segment: 01. public class Person 02. { 03. public string Name { get; set; } 04. public int Age { get; set; } 05. public string[] Languages { get; set; } 06. } 07. public static Person ConvertToPerson(string json) 08. { 09. var ser = new JavaScriptSerializer(); 10. 11. } You need to ensure that the ConvertToName() method returns the JSON input string as a Name object. Which code segment should you insert at line 10? A) Return ser.ConvertToType(json); B) Return ser.DeserializeObject(json); C) Return ser.Deserialize(json); D) Return (Person)ser.Serialize(json);
C) Return ser.Deserialize(json);
851
``` You are developing an application that includes the following code segment: interface ILion { void Run(); } interface IMan { void Run(); } ``` ``` You need to implement both Run() methods in a derived class named Animal that uses the Run() method of each interface. Which two code segments should you use? A) var animal = new Animal(); ((ILion, IMan)animal).Run(); B) class Animal : ILion, IMan { public void IMan.Run() { ... } public void ILion.Run() { ... } } C) class Animal : ILion, IMan { void IMan.Run() { ... } void ILion.Run() { ... } } D) var animal = new Animal(); ((ILion)animal).Run(); ((IMan)animal).Run(); E) var animal = new Animal(); animal.Run(ILion); animal.Run(IMan); F) var animal = new Animal(); animal.Run(); ```
``` B) class Animal : ILion, IMan { public void IMan.Run() { ... } public void ILion.Run() { ... } } ``` D) var animal = new Animal(); ((ILion)animal).Run(); ((IMan)animal).Run();
852
Suppose you’re creating an application; in the application you need to create a method that can be called by using a varying number of parameters. What should you use? A) derived classes B) interface C) enumeration D) method overloading
D) method overloading
853
Suppose you’re creating an application that needs a delegate that can hold a reference of a method that can return bool and accept an integer parameter. How would you define that delegate? A) delegate bool myDelegate(int i, int j); B) delegate bool (int i, int j); C) delegate myDelegate(int i, int j); D) delegate bool myDelegate(int i);
A) delegate bool myDelegate(int i, int j);
854
``` Which property or method of task can be used as an alternative of the await keyword? A) Result B) Wait() C) WaitAll() D) Delay() ```
A) Result
855
``` You’re creating an application that has many threads that run in parallel. You need to increment an integer variable “i". How would you increment it in an atomic operation? A) int i = 0; Interlocked.Increment(ref i); B) int i = 0; Interlocked.Increment(i); ``` ``` C) int i = 0; i++; D) int i = 0; Interlocked.Increment(out i); ```
A) int i = 0; Interlocked.Increment(ref i);
856
``` Suppose you’re creating a method that threw a new exception but it also threw an inner exception. See the following code: 01. private void myMethod(int i) 02. { 03. try 04. { 05. ... 06. } 07. catch (ArgumentException ex) 08. { 09. 10. } 11. } You must preserve the stack trace of the new exception and also throw the inner exception; which code statement would you use in line 09? A) throw ex; B) throw new Exception("Unexpected Error", ex); C) throw; D) throw new Exception(ex) ```
B) throw new Exception("Unexpected Error", ex);
857
``` Suppose you’re developing an application and you want to make a thread-safe code block for execution. Which of the following code blocks would you use to write code? A) object o = new object(); lock (o) { ... } B) object o = new object(); lock (typeof(o)) { ... } Chapter 16 ■ Practice Exam Questions 429 C) lock (new object ()) { ... } D) lock { ... } ```
``` A) object o = new object(); lock (o) { ... } ```
858
``` Which of the following is the right syntax for using an asynchronous lambda expression? A) Task task = async () => { … }; B) Task task = async () => { … }; C) Func task = async () => { … }; D) Action task = async (t) => { … }; ```
C) Func task = async () => { … };
859
``` When running a long-running asynchronous operation that returns a value, which keyword is used to wait and get the result? A) await B) yield C) return D) async ```
A) await
860
``` Which of the following collections is a thread-safe? A) Dictionary B) Stack C) ConcurrentDictionary D) Queue ```
C) ConcurrentDictionary
861
``` Which keyword is useful for returning a single value from a method to the calling code? A) yield B) return C) break D) continue ```
A) yield
862
``` Foreach loop can only run on: A) anything B) collection C) const values D) static values ```
B) collection
863
``` In a switch statement, which keyword would you use to write a code when no case value satisfies? A) else B) default C) return D) yield ```
B) default
864
``` How would you chain the execution of a task so that every next task runs when the previous task finishes its execution? Which method you would use? A) task.ContinueWith() B) Task.Wait() C) Task.Run() D) Thread.Join() ```
A) task.ContinueWith()
865
``` Which of the following methods is useful for holding the execution of a main thread until all background tasks are executing? A) Thread.Sleep() B) Task.WaitAll() C) Task.Wait() D) Thread.Join() ```
B) Task.WaitAll()
866
``` Which of following methods is accurate for holding the execution of a running task for a specific time? A) Thread.Sleep() B) Task.Delay() C) Task.Wait() D) Task.WaitAll() ```
B) Task.Delay()
867
``` When handling an exception, which block is useful to release resources? A) try B) catch C) finally D) lock ```
C) finally
868
``` Which keyword is used to prevent a class from inheriting? A) sealed B) lock C) const D) static ```
A) sealed
869
``` await keyword can only be written with a method whose method signature has: A) static keyword B) async keyword C) lock keyword D) sealed keyword ```
B) async keyword
870
``` Which of the following loops is faster? A) for B) do C) Parallel.for D) foreach ```
C) Parallel.for
871
``` Which of the following keywords is useful for ignoring the remaining code execution and quickly jumping to the next iteration of the loop? A) break; B) yield; C) jump; D) continue; ```
D) continue;
872
``` You need to reference a method which returns a Boolean value and accepts two int parameters. Which of the following delegates would you use? A) Func func; B) Action act; C) Func func; D) Action act; ```
A) Func func;
873
``` You’re creating an application that contains the following code: class Test { public event Action Launched; } class Program { static void Main(string[] args) { Test t = new Test(); } } How would you subscribe a Launched event in the Main method to the “t” instance? A) t.Launched += ()=>{..}; B) t.Launched = ()=>{..}; C) t.Launched -= ()=>{..}; D) t.Launched = t.Launched + ()=>{…}; ```
A) t.Launched += ()=>{..};
874
``` How do you throw an exception so the stack trace preserves the information? A) throw; B) throw new Exception(); C) throw ex; D) return new Exception(); ```
A) throw;
875
``` To create a custom exception, which class is required to be inherited? A) SystemException B) System.Exception C) System.Attribute D) Enumerable ```
B) System.Exception
876
An exception is handled on a method which mathematically calculates numbers. The method contains the following catch blocks: 01. 02. catch(ArithmeticException e) { Console.WriteLine("Arithmetic Error"); } 03. 04. catch (ArgumentException e) { Console.WriteLine("Invalid Error"); } 05. 06. catch (Exception e) { Console.WriteLine("General Error"); } 07. You need to add the following code to the method: catch (DivideByZeroException e) { Console.WriteLine("Divide by Zero"); } At which line should you insert the code? A) 01 B) 03 C) 05 D) 07
A) 01
877
A method name LongRunningMethod(CancellationTokenSource cts), takes a cancellation token source and performs a long-running task. If the calling code requests cancellation, the method must Cancel the longrunning task and set the task status to TaskStatus.Canceled. Which of the following methods should you use? A) throw new AggregateException(); B) ct.ThrowIfCancellationRequested() ; C) cts.Cancel(); D) if (ct.IsCancellationRequested) return;
B) ct.ThrowIfCancellationRequested() ;
878
``` Which class should you preferably use for tracing in Release Mode? A) Debug B) Trace C) TraceSource D) All of the above ```
C) TraceSource
879
``` To build a project you need a PDB file of: A) Previous build version B) Any build version C) No need of PDB file D) Same build version ```
D) Same build version
880
``` Which method is the easiest way of finding the problem if you have no idea what it is? A) Using Profiler B) Profiling by Hand C) Using Performance Counter D) Debugging ```
A) Using Profiler
881
``` Which of the following commands is required to create a strong name key? A) sn -k {assembly_name}.snk B) sn k {assembly_name}.snk C) gacutil -i {assembly_name}.snk D) gacutil i {assembly_name}.snk ```
A) sn -k {assembly_name}.snk
882
``` Which of the following methods is used for getting the information of the current assembly? A) Assembly. GetExecutingAssembly(); B) Assembly.GetExecutedAssembly(); C) Assembly.GetCurrentAssembly(); D) Assembly.ExecutingAssembly(); ```
A) Assembly. GetExecutingAssembly();
883
Which bindingflags are useful for getting the private data instance? A) BindingFlags.NonPublic | BindingFlags.Instance B) BindingFlags.Private | BindingFlags.Instance C) BindingFlags.NonPrivate | BindingFlags.NonStatic D) BindingFlags.Private | BindingFlags.NonStatic
A) BindingFlags.NonPublic | BindingFlags.Instance
884
``` The application needs to encrypt highly sensitive data. Which algorithm should you use? A) DES B) Aes C) TripleDES D) RC2 ```
B) Aes
885
You are developing an application which transmits a large amount of data. You need to ensure the data integrity. Which algorithm should you use? A) RSA B) HMACSHA256 C) Aes D) RNGCryptoServiceProvider
B) HMACSHA256
886
Salt Hashing is done by: A) Merging data with random value and perform cryptography. B) Merging data with random value and perform cryptanalysis. C) Merging data with random value and perform encryption. D) Merging data with random value and perform hashing
D) Merging data with random value and perform hashing
887
``` You want to retrieve data from Microsoft Access 2013, which should be read-only. Which class you should use? A) SqlDataAdapter B) DbDataAdapter C) OleDbDataReader D) SqlDataReader ```
C) OleDbDataReader
888
``` Suppose you created the ASMX Web Service named SampleService. Which class you would use to create the proxy for this service? A) SampleServiceSoapClient B) SampleService C) SampleServiceClient D) SampleServiceSoapProxy ```
A) SampleServiceSoapClient
889
Choose the correct code snippet/snippets for insert query (insert code snippet of C#, syntax vise): A) SqlConnection con=new SqlConnection(“ConectionString”); SqlCommand cmd=new SqlCommand(insertQuery,con); Con.open(); Cmd.ExecuteNonQuery(); Con.close(); B) Using(SqlConnection con=new SqlConnection(“ConectionString”)) { SqlCommand cmd=new SqlCommand(insertQuery,con); Cmd.ExecuteNonQuery(); } C) SqlConnection con=new SqlConnection(“ConectionString”); Using( SqlCommand cmd=new SqlCommand(insertQuery,con)) { Con.open(); Cmd.ExecuteNonQuery(); } D) Using(SqlConnection con=new SqlConnection(“ConectionString”)) { SqlCommand cmd=new SqlCommand(insertQuery,con); Con.Open(); Cmd.ExecuteNonQuery(); }
A) SqlConnection con=new SqlConnection(“ConectionString”); SqlCommand cmd=new SqlCommand(insertQuery,con); Con.open(); Cmd.ExecuteNonQuery(); Con.close(); D) Using(SqlConnection con=new SqlConnection(“ConectionString”)) { SqlCommand cmd=new SqlCommand(insertQuery,con); Con.Open(); Cmd.ExecuteNonQuery(); }
890
``` You are developing an application that retrieves Person type data from the Internet using JSON. You have written the following function for receiving the data so far: serializer.Deserialize(json); Which code segment should you use before this function? A) DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person)); B) DataContractSerializer serializer = new DataContractSerializer(typeof(Person)); C) JavaScriptSerializer serializer = new JavaScriptSerializer(); D) NetDataContractSerializer serializer = new NetDataContractSerializer(); ```
C) JavaScriptSerializer serializer = new JavaScriptSerializer();
891
``` Question 2 You need to store a large amount of data in a file. Which serializer would you consider better? A) XmlSerializer B) DataContractSerializer C) DataContractJsonSerializer D) BinaryFormatter E) JavaScriptSerializer ```
D) BinaryFormatter
892
``` You want to serialize data in Binary format but some members don’t need to be serialized. Which attribute should you use? A) XmlIgnore B) NotSerialized C) NonSerialized D) Ignore ```
C) NonSerialized