C# Certification Flashcards
70-483 Certification Exam Review
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?
Last visited (LIFO= Stack)
Answer = Stack
The following code is boxed into object o.
double d = 34.5;
object o = d;
You are asked to cast “object o” into “int”.
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;
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:
- Return a string that includes the player name and the number of coins
- Display the number of coins without leading zeros if the number is 1 or greater
- 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
Format specifier D formats integer digits with optional negative sign.
Answer = string.Format($”Player {name}, collected {coins:D3} coins”);
How do you encapsulate an array of integers into an indexer?
private int[] array;
public int this[int index] { get {return array[index];} set { array[index] = value;} }
Is the following method “Display” considered to be overloaded?
class Person { public void Display() { }
public int Display()
{
}
}
No
Overloading refers to different parameter types. The display method has different return types.
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:
- The value must be accessed by code within the Player class
- The value must be accessed to derived classes of Player
- 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?
protected get;
private set;
Suppose you are developing an application. The application has two classes named Player and Person.
The Player class must meet the following requirements
- It must inherit from the Person class
- It must not be inheritable by other classes in the application.
Which code segment should you use?
sealed class Player : Person {
}
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.
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();
Which type cannot be instantiated? A enum type B static type C class type D System.Object type
B. Static type
Which operator is used to get instance data inside type definition?
this
What is the code segment for defining implicit type conversion for a Person class?
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;
}
Which operator is used to compare types?
A) as
B) is
C) this
D) ?
B) is
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.
static class Extension { public static void ExtensionMethod(this int i) {
}
}
Which jump statement will you use to start the next iteration while skipping the current iteration of loop?
Continue
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#?
string name = n??”No Name”;
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.
I would do this….
return string.IsNullOrWhiteSpace(name) ? false: true;
or
return name==null?false: true;
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.
void Show(params int[] arg)
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) Convert.toInt32()
C) int.parse()
What collections stores values in Key, Value pairs?
Dictionary
SortedList
HashTable
To control how objects are compared, what interface is implemented
IComparable
Last In, First Out data structures are represented as?
Stack
First In, First Out structures are represented as?
Queue
When are generic collection classes appropriate?
When all objects are of the same type
What namespace is inherited by the following data structures?
Dictionary List Queue Stack SortedList
System.Collections.Generic
What namespace is inherited by the following data structures?
ArrayList HashTable Queue Stack SortedList
System.Collections
Arrays inherit from what namespace?
System.Array
What object used with a DataSet is used to add, update or delete records from a database?
DataAdapter
How is a dataset populated with data?
using the DataAdapter
What is a DataSet
A disconnected resultset that contains one or more data tables
What method returns the data represented as XML
ExecuteXMLReader
What method is used to return a single value from a database such as when a query returns a Sum or Count
ExecuteScalar
What object is a read-only, forward-only cursor connected to the database?
DBDataReader
What method is used to execute non-result returning queries such as Insert, Update or Delete
ExecuteNonQuery
What object is used to call a stored procedure or execute a dynamic SQL statement?
The Command object
What is ADO.Net?
A set of classes used to execute commands on a database
An ORM tool that masks the syntax for using ADO.Net to communicate with a database is referred to as?
Entity Framework
Classes are representative of what within Entity Framework Model
objects in the database
Within the Entity Framework Model, stored procedures are represented as what?
Methods
How are parameters passed by WCF Data Services to query a database?
By passing the parameters within the URL query string
What data formats are returned by WCF Data Services?
OData Adam
JSON
What protocol is used by WCF Data Services?
OData
What purpose does the await command serve?
Kicks off the method and returns processing to the calling method until the method completes
The async keyword must modify what in order to use the await keyword?
The method signature
In C# 5.0 and later, what keywords are used to perform asynchronous operations?
asynch & await
What classes are used to read and write string data
StringWriter
StringReader
Name three methods used by StreamReader to get the contents of a file.
Character by Character
Line by Line
Entire File at once
What is the default character encoding for StreamReader and StreamWriter
UTF-8
What classes are used for reading and writing characters by using an encoded value to convert the characters to and from bytes?
StreamReader
StreamWriter
What classes are used for reading or writing binary values?
BinaryReader
BinaryWriter
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
What objects are used to determine properties of a file and also performs operations on a file
File and FileInfo
In LINQ, what is an outer sequence?
The sequence calling the Join method
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.
LINQ statements executed in a where clause for a query expression is called it’s..?
Predicate
LINQ statements that select a subset of properties from a type that creates a new anonymous type is referred to as ?
Projection
A feautre of LINQ that enables you to query any type that implements the IEnumerable or IQueryable interface is called?
Query expression
A set of features that extends query capabilities to C# is called?
Language Integrated Query
or
LINQ
In LINQ, what is an inner sequence?
When using a method based join, the sequence passed to the join as a parameter.
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
What operator is the”goes to” or “such that” operator?
=>
Used primarily in lambda expressions
Execution of a LINQ query is deferred until the result is enumerated.
This is referred to as ?
Deferred execution
Define a composite key
Contains multple properties that are needed to complete a join.
A type created with read-only properties without having to write the code to declare the class is referred to as an….?
Anonymous type
What class is used in a LINQ to XML query to return the result of a query in XML?
XElement
What LINQ method allows you to return a distinct list of elements from a sequence?
Distinct
What LINQ method allows you to return a limited number of elements from a sequence.
Take
What LINQ method allows you to skip a specific number of elements in a sequence?
Skip
In LINQ, how are two sequences concatenated?
Concat
When using method based LINQ queries, how are out joins formed?
GroupJoin
In LINQ, what is the purpose of the SelectMany method?
To flatten two sequences into one result, similar to join.
Which LINQ query uses lambda expressions as parameters to methods?
Method based queries
What is the difference between method based queries and query expressions?
Syntax, no functional difference.
In LINQ, a group by clause returns what data type?
IGrouping
How is a LINQ composit key formed?
By specifying an anonymous type in the join clause
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.
What keyword is used to join properties in LINQ?
Equals
Define projection
Creating a custom type in a select clause of a query expression using a limited number of properties from the original object.
What query expression clause is used to sort the results on one or more properties?
OrderBy
How are multiple where clauses implemented using LINQ?
By using the && operator
Define the predicate in LINQ
All code contained within the Where clause
How are joins evaluated in LINQ queries?
Joins are always equivalence based
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()
When does execution of a LINQ query occur?
When the result is enumerated
Define a LINQ clause
A query expression containing Select, GroupBy, Where or joins
By convention, the results of a LINQ query are stored where?
To a variable of type var, allowing the result to be implicitly typed.
What object can be queried by LINQ?
Any object that implements IEnumerable or IQueryable
Define the correct order of keywords for a LINQ query expression.
from…
where …
select …
Define a statement that returns the count of all even numbers
var count = myNumbers.Where(i => i %2 == 0) .Count()
Define a statement that groups a sequence by the State property
var states = myStates.GroupBy(s => s.name);
Define a statement that creates an anonymous type
.Select( new {h.city, h.state})
What two keywords must you use in a join clause to create an outer join?
into
DefaultIfEmpty
Define a clause that joins two sequences on the stateId property
on e.stateId equals s.stateId
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}
Define a LINQ clause that orders by state and then by city
Orderby h.state, h.city
Define a WHERE clause that returns all integers between 10 and 20
Where i >= 10 && i <= 20
Define the extension LINQ method used to find the first item in a sequence
First or Take
Define how to find the minimum value in a sequence
(from i in myArray
selecti).Min()
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
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;
Name two methods of performing customized serialization
Attributes (the preferred method)
Implement Iserializable
What class is used to perform binary serialization.
BinaryFormatter
XML serialization is performed by what class?
XMLSerializer
What class is used to perform JSON serialization
DataContractJsonSerializer
What is serialization?
The process of transforming an objects data to persisted storage or to transfer the object from one domain to another
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
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
The most basic type used to store a set of data is called?
Array
What is the role of the keyword async?
Indicates that the method, lambda expression, or anonymous method is asynchronous
What keyword suspends the execution of a method until the awaited task completes?
await
The process of converting a reference type to a value type is called?
unboxing
What is boxing?
The process of converting a value type to a reference type
What is a collection?
A generic term encompassing lists, dictionaries, queues, stacks, hash tables and other objects that contain sets of data.
The object in ADO.NET that allows you to open and execute commands against a database is called?
A connection object.
What is the IComparable interface?
Implements an interface that can be sorted when used in a collection or array.
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
What is JSON?
JavaScript Object Notation
A lightweight data-interchange format
A computer software term for tools that convert data between type systems using an object oriented programming language is called?
ORM
Object Relational Mapping
The XML representation of data returned from an OData query is called?
OData ATOM
What is OData?
Open Data Protocoal
A web protocol for querying and updating data over the intranet or internet
Creating a new copy of an object that copies all value types and copies object references for reference types is called a ?
shallow copy
The process of converting an object into a stream of bytes that can be stored or transmitted is called?
serialization
Define stream.
An abstract class that provides a generic view of a sequence of bytes.
What is a T4 template?
A file that contains text blocks and control statements that enable you to generate a code file.
What enables you to use OData to expose and consume data over the web or intranet?
WCF Data Services
WCF=(Windows Communication Foundation)
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.
You are using a queue and you want to add a new item.
Which method do you use?
Enqueue
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
What must be implemented when creating custom collections?
Both IEnumerable and IEnumerable
What collection stores values in memory as a last-in-last-out structure?
Stack, Stack
What collection stores value in memory as a first-in-first-out structure?
Queue, Queue
What collection stores unique items and offer set operations?
HashSet
What is a dictionary?
A collection that stores and accesses items via key/value pairs.
What is the most used collection?
List, List
Define an Array
The most basic collection type which is constrained by a fixed size
When given the opportunity to use the generic or non-generic collection, which is generally preferred?
Always use generic where possible.
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
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.
JSON text formatted files are created in .NET using what class?
DataContractJsonSerializer
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
WCF serialization is performed using what class?
DataContractJsonSerializer
How is binary serialization performed in .NET?
Using the BinaryFormatter class
How is the XMLSerializer configured?
Through the use of attributes.
What class handles XML serializtion?
XMLSerializer
What is deserialization
Takes a series of bytes or a flat file and transforms it to an object
What is serialization?
The process of transforming an object to a flat file or series of bytes
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
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?
- verify using System.Linq
2. Validate the datatype implements IEnumerable, IEnumerable
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();
When are LINQ queries executed?
Not until they are first iterated, known as deferred execution.
What is the primary function of LINQ?
To provide a uniform way of writing queries against multiple data stores.
Which ADO.NET command objects’s property would you use when a query returns the sum of a column in a table?
ExecuteScalar
Which property of an ADO.NET DataAdapter is used to insert records in a database?
InsertCommand
Which method of a DataAdapter is used to populate a DataSet?
Fill
Which ADO.NET object is fully traversable cursor and is disconnected from the database?
DataTable
Which ADO.NET command object’s property would you use when a query returns the sum of a column in a table?
ExecuteScalar
Which ADO.NET object is a forward-only cursor and is connected to the database while the cursor is open?
DBDataReader
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();
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();
}
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.
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
Which command object’s method would you use to execute a query that returns only one row and one column?
ExecuteScalar
Which command object’s method would you use to execute a query that does not return any results?
ExecuteNonQuery
Which properties of an ADO.NET command object must you set to execute a stored procedure?
CommandType
CommandText
Parameters
Which ADO.NET object is used to connect to a database?
Connection
Which collection would you use if you need to quickly find an element by its key rather than it’s index?
Dictionary
or
SortedList
Which collection would you use if you need to process the items in the collection on a last-in, first-out order?
Stack, Stack
Which collection would you use if you need to process the items in the collection on first-in, first-out order?
Queue, Queue
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?
- Inherit from IComparable
2. Implement CompareTo()
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
Which object does the variable mySet inherit from?
int[] mySet = new int[5];
System.Array
Custom collections must inherit from which base class?
CollectionBase
What is SSL?
Secure Socket Layer is a cryptographic protocol used for secure communication over the internet.
Define secured hash algorithm
SHA is a family of cryptographic algorithms used to calculate hashes published by NIST
What is the infrastructure required to handle digital certificates?
Public Key Infrastructure (PKI)
A family of cryptographic algorithms used to provide data integrity and authenticity is called?
Message Authentication Code (MAC)
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.
The result of compiling a .NET application from source code is called the?
Intermediate Language (IL)
A data array used by the encryption algorithm to encrypt the first data block is referred to as the?
Initialization Vector (IV)
Describe hashing.
Used to map data structures of variable length to fixed size data structures.
A data structure that holds items that share the same hash value is called?
Hash Bucket
What is the Global Assembly Cache?
The GAC is a machine-wide code cache
The process of decoding previously encrypted data so that it can be used by your application is?
Decryption
The process of encoding data so that it cannot be read by an unauthorized person is called?
Encryption
The practice and study of techniques for secure communication is called?
Cryptography
A list of digital certificates that have been revoked for various reasons is referred to as?
Certificate Revocation List (CRL)
Define the CLR
The Common Language Runtime is the component of the .NET Framework responsible for running .NET applications and managing the running environment.
Define Certificate Stores
A special storage location on your computer, used to store encryption certificates
What entity issues digital certificates?
Certificate Authority (CA)
Define asymmetric encryption
A criptographic algorithm that uses two complimentary keys. One for encryption and one for decryption.
What is an assembly?
An assembly is the unit of reuse, deployment, versioning and security.
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
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
You want to update a specific row in the database.
What commands are required?
- SqlConnection to establish connection to database
2. SqlCommand to execute the query
Name the four classes used to manipulate XML.
XmlReader
XmlWriter
XPathNavigator
XmlDocument
Why should you use parameterized queries when performing CRUD operations?
To avoid Sql injection
Under ADO.NET, how are connections made to the database?
Using the DBConnection object
What is ADO.NET?
A provider model that enables you to connect to different types of databases.
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
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
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
What namespace supports WebRequest and WebResponse?
System.Net
What classes are used for performing network requests?
WebRequest
WebResponse
What class implementation is used for dealing with files, network operations and other types of IO
Stream
Define streams
An abstract method for working with a series of bytes
What methods are available to create and parse file paths?
static Path class
What methods are provided to work with files?
File
FileInfo
How are folders manipulated programmatically?
Directory
DirectoryInfo
How are drives manipulated programmatically?
Drive
DriveInfo
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);
What is a strong name assembly?
A signed assembly
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
How can you deploy a strong named assembly?
Run gacutil.exe or copy file to bin folder or create an installer
Describe the components of a strong named assembly
Name Version Public Key Token Culture Processing Architecture
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);
Write a code snippet to calculate the secure hash of a byte array called userData using the SHA algorithm
sha.ComputeHash(userData);
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
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
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.
When is a MAC algorithm recommended?
To ensure both authenticity and integrity is required
When is the hashing algorithm recommended?
When data integrity is the only requirement
When is asymmetric encryption recommended?
If you do not have a way to send data securely
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.
How is the encryptor/decryptor used?
Directly, using TransformFinalBlock or sending to CryptoStream
How is symmetric encryption instantiated?
By calling
CreateEncryptor
CreateDecryptor
What is required to perform symmetric encryption?
An initialization vector (IV) used to encryp the first block of data.
Define symmetric encryption
Encryption based on a shared secret
How many keys are used in asymmetric encryption?
Two
- Private key
- Public key
Define asymmetric encryption
Based on a pair of complimentary keys. Data encrypted by one key can be decrypted by the other.
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}$)
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}$
Write a regular expression matching the social security number format ###-##-#### where # is any digit.
^\d{3}-\d{2}-\d{4}$
What method returns true if a regular expression matches a string?
Regex.IsMatch
What is the best use of performance counters?
To determine how often a particular operation is occurring on the system as a whole.
True or False
Whan an assertion fails in debug builds, the Debug.Assert method allows you halt, debug the program or continue running?
True
True or False
The program must continue running even if a Debug.Assert method stops the program
True
True or False
The Debug.Assert method is ignored in release builds
True
What builds define the TRACE symbol?
Debug and Release
What builds define the Debug symbol
Debug
How can you prevent Visual Studio from creating a .pdb file?
Setting the value of PDB file type to “None”
What file is required to debug a compiled executable?
.pdb file
What statements are used to trace or log a program’s execution?
DEBUG
and
TRACE
The process of making the program record key events in a log file is referred to as?
logging
The process of instrumenting a program to track what is doing is referred to as ?
Tracing
What method would you use to investigate bottlenecks in a program?
Use an automatic profiler
What statement can be used to validate data as it moves through a program?
Debug.Assert
How are preprocessor symbols disabled?
UNDEF
What processor directives define preprocessor symbols?
DEFINE
How can you determine what code is included in a program?
By using directives #if #elif #else #endif
What is the purpose of the #line directive?
To change the line number or name of file reported as errors
How are custom warnings and/or errors added to the error list?
by using
#warning
or
#error
What is the syntax to create collapsible code regions?
#region .. #endregion
What is the syntax to disable a warning?
pragma warning disable
What is the syntax to restore a warning?
pragma warning restore
Where is the predefined constant TRACE defined?
In the debug and release builds
Where is the predefined constant DEBUG defined?
In the debug builds
Calls to DEBUG and TRACE are ignored if?
Both DEBUG and TRACE are not defined
Useful DEBUG and TRACE methods include?
Assert Fail Flush Indent Unindent Write WriteIf WriteLine WriteLineIf
When adding standard listeners to Debug and Trace objects, where are messages written to?
- Output window
- Event logs
- Text files
What file is used to debug a compiled executable?
.pdb
What directives are used to implement tracing?
DEBUG
and
TRACE
Instrumenting a program to trace it’s progress is known as?
Tracing
Name the methods to support logging
- Writing to a text file
- Using DEBUG and TRACE with a listener to write to a
text file - Writing to an event log
The recording of key events is known as?
logging
What methods are used to support profiling?
- Using a profiler
- Instrumenting code by hand
- Performance counters
Gathering information about a program to study characteristics such as speed and memory usage is referred to as?
Profiling
A test on data ot see if the data makes sense is referred to as a ?
sanity check
What is tracing?
The process of instrumenting a program so that you can track what it is doing
What is a regular expression?
An expression in regular expression language that defines a pattern to match.
What is profiling?
The process of instrumenting a program to study it’s speed, memory, disk usage, or other performance characteristics.
An automated tool that gathers performance data for a program by it’s code or by sampling is referred to as?
a profiler.
What is a performance counter?
A system-wide counter used to track some type of activity on the computer.
A regular expression used for matching parts of a string is called?
a pattern
What is logging?
The process of instrumenting a program so it records key events?
Adding features to a program to study the program itself is called?
instrumenting
Options set in a regular expression using the syntax
(?imasx) are referred to as ?
inline options
A sequence of characters that have special meaning in a regular expression is referred to as a ?
escape sequence
Define data validation
Program code that verifies that a data value makes sense
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
A regular expression construction that represents a set of characters to match is?
character class
A piece of code that makes a particular claim about data and throws an exception if that claim is false is called?
An assertion
What method is used to create assertions?
System.Diagnostics.Debug.Assert
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});
Which method of the MethodInfo class can be used to execute the method using reflection?
Invoke
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);
Which property of the Type class can you use to determine the number of dimensions in an array?
GetArrayRank
Which class in the System.Reflection namespace is used to represent a field defined in a class?
FieldInfo
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
Which class would you create if you wanted to determine all properties contained in a class using reflection?
Type
Create an instance of a DataTable using reflection
myAssembly.CreateInstance(“System.Data.DataTable”);
Which method should you call if you want .NET Framework to look in the load-from context?
LoadFrom
Which method should you call if you want the .NET Framework to look in the load-context to load an Assembly?
Load
Define the syntax to load an assembly
- Assembly.Load(“System.Data”,
Version=4.0.0.0,
Culture = neutral,
PublicKeyToken=b77a5c561934e089); - Assembly.LoadFrom(@”c:\myProject\Project1.dll”);
- Assembly.LoadFile(@”c:\myProject\Project1.dll”);
- Assembly.ReflectionOnlyLoad(“System.Data”,
Version=4.0.0.0,
Culture = Neutral,
PublicKeyToken=b77a5c561934e089);
Which method of the Assembly class returns an instance of the current assembly?
GetExecutingAssembly
Which property of the Assembly class returns the name of the assembly?
FullName
Which method of the Assembly class allows you to get all the public types defined in the assembly?
GetExportedTypes
Which class in the System.Reflection namespace would you use if you want to determine all the classes contained in the .dll file?
Assembly
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;} }
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();
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?
- Create an instance of the assembly class
- Load the assembly
- Call the GetReferencedAssemblies method
What code creates a lambda expression returning the squares of an integer?
x => x * x;
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
The process that permits parameter types that are less derived than the delegate type?
Contravariance
The process that enables you to have a method with a more derived return type than the delegate return type is ?
Covariance
The => symbol in a lambda expression is referred to as?
goes to
or
such that
What is a delegate?
A type that references a method
Shorthand syntax for anonymous functions are referred to as?
lambda expressions
What class generates the class file in either C#, VB or JScript?
System.CodeDom.CodeDomProvider
In the codeDom, what class is the top level class?
System.CodeDom.CodeCompileUnit
What is the CodeDom?
Code Document Object Model
As set of classes that enables you to create code generators
Custom attributes inherit from what class?
System.Attribute
How is an attribute declared?
By decorating with square brackets []
What enables you to create metadata for a class, property or method?
Attributes
What method returns a PropertyInfo object and enables you to set or get a property’s value?
Type.GetProperty
What does System.Type represent?
A class, interface, array, value type, enumeration, parameter, generic type definition and open or closed generic types.
What method creates an instance of a type?
Assembly.CreateInstance
What method loads the assembly but does not enable execution?
Assembly.ReflectionOnlyLoad
What method loads an assembly into memory and enables you to execute code?
Assembly.Load
What class is used to examine the types within an .exe or .dll file?
System.Reflection.Assembly
Name the two ways to get a reference to the Type object
typeof()
and
.GetType()
What is a type?
A class, interface, array, value type, enumeration, parameter, generic type definition, open or closed generic type.
The class, porperty or method that contains metadata defined by an attribute is called the…?
Target
A lamdba expression containing more than one statement in the body of the expression is referred to as a …?
statement lambda
What is reflection?
Provides lasses that can be used to read metadata or dynamically invoke behavior from a type?
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
A file, typically a .dll or .exe that composes an assembly is referred to as a ..?
module
When loading an assembly using reflection, what context contains the assemblies located inthe path passed into LoadFrom method.
load-from context
When loading an assembly during reflection, what context contains the assemblies found by probing
load context
Define a lambda expression
Shorthand syntax for an anonymous method that can be associated with a delegate or expression tree.
A variable in a class or structure is referred to as a ..?
field
Code in a tree-like structure where each node is an expression is referred to as a…?
Expression tree
What is an expression lambda?
An expression that contains one statement for the body.
What type is a reference to a method?
delegate
Define covariance
Enables you to have a method with a more derived return type than the delegates return type
Define contravariance
Permits parameter types that are less derived than the delegates parameter types.
When loading an assembly using reflection, where does reflection search for the assembly?
in the context
Define the CodeDOM
Code Document Object Model
Enables the developer to generate code in multiple languages at run time based on single code set.
What enables you to associate metadata with assemblies, types, methods, properties…?
attributes
A compiled piee of code in a .dll or .exe is referred to as a ?
assembly
What method enables you to associate a block of code with a delegate without a method signature?
anonymous methods
If during Garbage Collection a program has no path of references that access the object, the object is ?
unreachable
Resources that are not under the control of the CLR are known as?
unmanaged resources
A base or parent class is also known as?
the superclass
The process of deriving a subclass from a base class through inheritance is referred to as ?
subclassing
What is a subclass?
A derived class
Classes that have the same parent class are referred to?
sibling class
A copy of an object where reference fields refer to the same objects as the original is a ..?
shallow clone
If the program has a path of references that allow access to the object than it is?
reachable
A base, or superclass is known as the?
parent class
Because you cannot direct when the GC will call an objects Finalize method, the process is referred to as ?
Nondeterministic finalization
Allowing a child class to have more than one parent class?
multiple inheritance (not allowed in C#)
Resources that are under the control of the CLR are?
managed resoources
Using an interface to require a class to provide certain features much as inheritance does is referred to as ?
Interface inheritance
What does it mean to inherit?
A derived class inherits the properties, methods, events and other code from the base class.
The process that executes periodically to reclaim memory that is no longer accessible to the program
Garbage Collection (GC)
What is Garbage Collection?
The process of running the Garbage Collector to reclaim memory no longer available to the program
A queue through with object with finalizers must pass before being destroyed is called the ?
finalization queue
What is finalization?
The process of the garbage collection calling the objects Finalize method.
What is a destructor?
A method with no return type and the class name preceded by the ~ symbol
A class’s children, as well as their children are referred to as?
descendant class
The creation of one class based on another through inheritance is referred to ?
deriving a class
A copy of an object where reference fields refer to new instances of objects?
deep clone
A virtual machine that manages C# ( and other .NET) programs is the ?
Common Language Runtime (CLR)
A class derived from a parent class is referred to as the ?
child class
A class from which another class is derived via inheritance is referred to as the ?
base class
A class parent is referred to as an ?
ancestor class
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.
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.
What resources are freed by a destructor?
unmanaged resources
What resources should be freed in a Dispose method?
manage and unmanaged resources
Yes or No
Can a dispose method be executed more than once?
Yes
Yes or No
For classes with only unmanaged resources, should IDisposable be implemented?
Yes and it needs to implement a destructor
Yes or No
For classes with managed resources, should IDisposable be implemented?
Yes, but a destructor is not required
Yes or No
Do classes with no managed or unmanaged resource require an implementation of IDisposable?
No
A destructor is not required
What methods are destructors converted to by the compiler?
Finalize
Yes or No
Can access modifiers or parameters be defined on a destructor?
No
True or False
Destructors can be inherited or overloaded?
False
How many destructors can be assigned to a class?
No more than one
True or False
Destructors may be defined in structs and classes
False
Destructors are only defined in classes
How are objects added to an IEnumerator result
yield return
Which interface returns an object used for moving through lists of objects?
IEnumerable
What method of ICloneable returns a copy of the object?
Clone
What interface provides an equal method to determine if two objects are equal to one another?
IEquatable
What interface provides a Compare method to compare two objects to determine their ordering?
IComparer
What method from IComparable is provided to determine the order of objects?
CompareTo
When code can use either a class instance or interface instance to access the interface, then the interface was implemented how?
implict
Define interface inheritance
The act of implementing an interface
If a class implements an inteface explicitly, how is the explicit reference acessed?
It must use an interface instance
How many classes and interfaces can a class inherit?
one class any number of interfaces
Buy convention, interface names begin with what letter?
I (IEnumerable, etc)
True or False
If a parent class has constructors, the child class constructor must invoke them directly or indirectly
True
True or False
At most, a constructor can invoke one base class or one same class constructor.
True
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; }
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 } }
Does C# support multiple inheritance?
No
If a class has unmanaged resources and no managed resources should IDisposable provide a destructor?
Yes
Implement IDisposable and provide a destructor
If a class has managed resources and no unmanaged resources should IDisposable provide a destructor?
No
Implement IDisposabel but provide no destructor
If a class implements IDisposable, what three steps should be completed by the Dispose method?
- Free the managed resources
- Free unmanaged resources
- Call GC.SuppressFinalize
True or False
Destructors are inherited?
False
True or False
Before destroying an object, the Garbage Collector (GC) calls it’s Dispose method?
False
The GC calls the Finalize method
The IEnumerable and IEnumerator interfaces provide what methods to move through a list of objects?
MoveNext
and
Reset
True or False
A class can inherit from at most one class and implement any number of interfaces
True
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
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
Is code reuse a goal of interface design?
No
The goals are
- Simulating multiple inheritance
- Treating unrelated objects in uniform way
- Polymorphism
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
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
If the base statement is declared first, can the constructor use a this statement and a base statement?
No
Does the use of the base keyword allow a constructor to invoke a different constructor in the same class?
No
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
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.
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.
When experience performance problems, what can you do to isolate and resolve root cause?
Profile the application
What classes are used to log and trace messages?
DEBUG
and
TRACE
When should logging and tracing be implemented?
from the beginning of the project
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
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
You are ready to deploy your code to a production server.
Which configuration do you deploy?
Release configuration
What build outputs code that can be deployed to production?
Release build
What tools are provided to give extra instructions to the compiler.
compile directives
What type of build outputs a nonoptimized version of the code that contains extra instruction to help debugging?
Debug build
The compiler can be configured in Visual Studio through use of what tool?
Build configurations
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
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?
- Deploy the assembly to the GAC
2. Strongly name the assembly
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.
How are applications bound to the assemblies they were developed with?
by using versioning
What is a WinMD assembly?
A special type of assembly used by WinRT to map non-native languages the native WinRT components.
Signed assemblies may be placed where?
inside the Global Assembly Cache (GAC)
To prevent tampering what may be done to an assembly?
Strongly signed
A compiled unit of code that contains metadata is referred to as an ?
assembly
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
You need to encrypt a large amount of data.
Which algorithm should yoour use?
AESManaged
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
What is the method used to verify the authenticity of an author?
Digital Certificates
What process is used to retrict the resources and operations an application can access and execute.
CAS
What is the purpose of System.Security.SecureString?
Maintains sensitive string data in memory
What is hashing?
The process of converting a large amount of data to a smaller hash code
What algorithm uses a public and private key that are mathematically linked?
Asymmetric algorithm
What algorithm uses the same key to encrypt and decrypt data?
Symmetric algorithm
You need to validate an XML file.
What do you use?
XML Schema Definition (XSD)
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);
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
When receiving JSON and XML files, it is important to validate them using what built-in types.
JavascriptSerializer
and
XMLSchemas
What can be used to match input against a specified pattern or replace specified characters with other values?
regular expressions
What functions are used to convert between types?
- Parse
- TryParse
- Convert
Where is data integrity managed?
By your application and your data store
Why is validating application input important?
To protect your application from mistakes and/or attacks
What steps are required to make sure data is not modified while transferred?
- Calculate the cryptographic hash
- Send the hash with the data
for validation by the receiving party.
Name two commonly used hashing algorithms?
SHA256
SHA512
Mapping binary data of a variable length to a fixed size binary data is called?
hashing
How are asymmetric private keys secured?
By using certificates or by using Crypto Service Providers containers
How are symmetric keys exchanged?
Using asymmetric algorithms
Name the four parts of an assembly version
Major
Minor
Build
Revision
Name the five parts of a strong name assembly
Friendly name Version Culture Public Key Token Processor Architecture
What is an assembly called that has been digitally signed?
strong named assembly
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.
What type of assemblies can be deployed to the GAC?
only strong named assemblies
What is the GAC?
Global Access Cache
A repository to share .NET assemblies
A cryptographic protocol used for secure communication ove the Internet, the successor of SSL is called?
Transport Layer Secuirty (TLS)
Which method would you call when you use a barrier to mark that a participant reached that point?
SignalAndWait
How can you schedule work to be done by a thread from a threadpool?
- Call the ThreadPool.QueueUserWorkItem
2. Create a new thread and set property
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
Define contravariance
Allow a method to take parameters that are from a superclass of the type expected by the delegate
Define covariance
Allows a method to return a value from a subclass of the result expected by a delegate
What methods can you use to catch integer overflow exceptions?
- 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
True or False
Can a try-catch-finally block next inside a try-catch-finally block?
Yes
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.
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
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);
How do you evaluate if the variable result holds the value
float.PositiveInfinity
- result == float.PostiveInfinity
- float.IsInfinity(result)
- float.IsPositiveInfinity(result)
Which of the following should you not do when building a custom exception class?
Make it implement IDisposable
How are events customized?
By adding a custom event accessor and by directly using the underlying delegate type
How are events raised?
Events are raised by the declaring class
Users of events can only remove or add methods to the invocation list.
Define events
A layer of ‘syntatic sugar’ on top of delegates to easily implement the publish/subscribe pattern.
Define lambda expression
Anonymous methods that use the => operator and form a compact way to create inline functions.
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
Define Task
A unti fo work
Define scheduler
A component of the OS that slices time between threads
Define race condition
Occurs when two or more threads access the same data for write operations
Define mutual exclusion
The problem of ensuring two threads can’t be in the same critical section at the same time.
Define multithreading
An operating system or hardware platform that can have several threads operating at the same time.
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)
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
Define
What four conditions lead to a deadlock
- Mutual exclusion
- Hold and Wait
- No preemption
- Circular wait
Define
Deadlock
Two or more threads that attempt to acquire a lock on a resource
Define
Atomic Operation
An operation that runs once without interruption by the scheduler
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
Define
Asynchrony
Operations run in a non-blocking fashion
How do you execute a method as a task?
- Create a new task, then call the Start method
- Create and run task (Task.Run())
- Create and run task via Task.Factory.StartNew()
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
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
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
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
You want your type to be able to be converted from string. Which interface should you implement?
IFormattable
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
You are parsing a lage piece of text to replace values based on some complex algorithm.
Which class should you use?
StringBuilder
Name six methods for dealing with strings
IndexOf LastIndexOf StartsWith EndsWith SubString
What is the purpose of StringBuilder?
To enhance the performance of string manipulations
Define strings
An immutable reference type
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.
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
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.
When is a WeakReference used?
To maintain a reference to items that can be garbage collected when necessary.
How can yo make sure resources are freed when implementing IDisposable?
By implementing a using statement
What is the purpose of IDisposable?
To free unmanaged resources in a deterministic way.
What piece of code is executed by the garbage collector when disposing of an object?
Finalizer
What comprises memory in a C# program?
Stack (local variables)
Heap (global variables, method/functions)
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
Memory allocation is managed on the heap by what process?
Garbage Collection (GC)
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
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)]
Define expression trees
Expression trees describe a piece of code.
Expression trees can be translated to something else (SQL) or compiled and executed.
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.
Define Reflection
The process of inspecting the metadata of a C# application
Define Attributes
A type of metadata that can be applied in code and queued at runtime
What is stored in a C# assembly?
Code and metadata
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
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.
Define IComparable
Interface used to sort elements
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.
Define IUnknown
Wrapper used to add com objects that are unable to be wrapped by the compiler
Define IDisposable
Facilitates working with external unmanaged resources
Define IEnumerable
Allows you to iterate over items in the collection
Name four primary default interfaces provided by the .NET framework
IComparable
IEnumerable
IDisposable
IUnknown
How can you prevent a class from being inherited?
Mark the class as sealed
What is the significance of marking a class abstract?
The class cannot be instantiated and can function only as a base class.
Name the three C# data structures
Structs
Enums
Classes
Where are value types defined?
Within the .NET Framework
How are value types based?
On the number of bits used to store the type
How are value types passed to methods?
As a copy
Value types are an alias for what object?
System
How are value types stored?
Directly
How are object values passed in generic methods?
They are passed by reference
What does the designator indicate in a generic class?
Serve as a placeholder that will contain the object used
What is an advantage of using Generics in .NET?
Generics enable you to create classes that accept the type at creation time.
Name on advantage of using named parameters
You can pass the parameters in to the method in any order using parameter names
Boxing refers to ?
Converting a value type to a reference type
How do enforce encapsulation on the data members of your class?
Create private data members
and
Public properties
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
What is the parameter in this method known as?
public void displayAbsoluteValue( int value = 1) { //Do Something }
Optional
What are two methods with the same name but with different parameters referred to as?
Overloaded methods
In the following enumeration, what will be the underlying value of Wed?
enum Days{Mon-1, Tues, Wed, Thur, Fri, Sat, Sun}
3
What is the correct way to access the firstname property of a struct named Student
var firstName = Student.firstname;
True or False
Can structs contain methods?
True
Which declaration can assign default value to an int type:
int myInt = new int();
True or False
double and float types can store values with decimals?
True
What is the maximum value you can store in an uint data type?
4,294, 967, 296
Define main property abstract methods
Abstract methods do not define and implementation
How are overloaded methods defined?
By signature name, types and parameters
What purpose do methods serve in classes?
Provide the functionality of the class
How many parameters may the default constructor specify?
None
Default constructors have no parameters
How are constructors named?
With the same name as the class
Do constructors specify a return type?
No
What is the purpose of the constructor?
To initialize the class
What is the purose of fields within a class?
To house data for the class
To avoid unwanted modifications, how should fields be marked?
private
Name the modifiers that can be used when declaring classes?
internal private public protected protected internal
What is the purpose of class modifiers?
To determine access for classes and class members
What is the purpose of member functions within a class?
To describe functionality
What is the purpose of member variables within a class?
To describe characteristics or properties
Reference types are commonly referred to as?
classes
What is the underlying type of enums?
Integers beginning at 0, unless the declaration specified in declaration specifies otherwise
How are enumerations formed?
As a list of named constants
How are structs passed to methods?
By value
Define structs
Lightweight data structures
How can derived classes act on base classes marked as virtual?
Derived classes can override virtual methods to add or replace behavior.
A class is limited to inheriting how many interfaces?
No limit, unlimited
A class is limited to inheriting how many classes?
One, C# support single class inheritance
Define interface
An interface specifies the public elements a type myst implement
Define inheritance
The process in which a class is derived from another class or from an interface
Define generic types
Type parameter used to make code more flexible
Name the types in C#
Value Types
Reference Types
Define casting
An explicit conversion that requires special syntax
Name the conversion options for types
Implicit
Explicit
Define boxing
Boxing occurs when a value type is treated as a reference type
What keyword can be used to ease the static typing of C# and improve interoperability with other languages
dynamic
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.
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.
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)
Name two uses of explicit interface implementation
- To hide information
2. Implement interfaces with duplicate signatures
Name the five access modifiers in C# development
private public internal protected protected internal
How is accessability to types and type elements restricted?
Through use of access modifiers
Define getters and setters
Property accessors that can run additional code
How is data encapsulated in object-oriented design?
Through use of properties
Why is encapsulation important in object-oriented design?
Hides internal details and improves usability of type
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.
You are creating a generic class that should work only with reference types.
Which type constraint should you add?
where T:struct
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
Define overriding
Enables you to redefine functionality from a base class in a derived class.
How are C# types created?
Using ; Constructors Methods Properties Fields Indexers
Which method will you use to Signal and EventWaitHandle?
set
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);
What code is equivalent with
lock(syncObject) { // Do something }
Monitor.Enter(syncObject);
try { } finally { Monitor.Exit(syncObject) }
Name methods that can be used to start or continue tasks
ContinueWith
WhenAll
WhenAny
Name two methods to create and start a task
- Task.Run()
2. Task.Factory.StartNew()
An asynchronous unit of work is known as a ?
Task
What instrument is used to reduce resource consumption when using threads?
Threadpools
Which class abstracts task creation and makes it easier to deal with loops and parallel invokation of methods?
Parallel
What class is used to run code in parallel?
The Parallel class
What extension is used to run queries in parallel?
PLINQ
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()
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.
What class is used to create threads explicitly?
Thread class
What class is used to allow runtime to handle threads?
Threadpools
What is the recommended method to handle multithreaded code?
The Task object
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
What operators are sued to write asynchronous code more easily?
async and await
What is the advantage of a thread?
Improves responsiveness and enables multiple CPU processing.
How do u describe a thread?
A virtualized CPU
What collection is used to work with data in a multithreaded environment?
Concurrent
Define anonymous method
A method without a name.
You create a delegate that refers to code the method should contain
How are delegates defined?
delegate(params) { // Do Something }
Ex. Func Square = delegate(float x)
{
return x * x;
};
What is the general form of a lambda expression?
() => statement
What is the general form of an asynchronous lambda?
async (params) => { // Do Something };
What is the general form of a statement lambda?
() => { // Do Something; return value; };
Define subscriber
The class that catches the event
Define publisher
An object that raises the event
What operators are used to subscribe/unsubscribe to an event?
\+= Subscribes -= Unsubscribe
Define syntax for declaring an event
AccessModifier event delegate eventName
Ex.
public delegate void customEventHandler();
public event customEventHandler eventName;
Describe the arguments passed to events
First parameter is the object raising the event
Second parameter is an object derived from EventArgs
Define eventArgs
Arguments relevant to the event
Describe form for declaring event arguments
class customEventArgs:EventArgs { // instance variables public customEventArgs(instance variables) { // Do someting } }
Define Microsoft’s generic EventHandler delegate
public event EventHandler customEventName
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
Define structure of inherited event
protected virtual void onMethod(customEventArg) { // Do something }
Define the statement that subscribes the myButton_Click event handler to catch the myButton controls click event.
myButton.Click += myButton_Click;
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?
- Create an OnAddress changed method in the Person class that raises the event.
- Make the Employee class call OnAddressChanged as needed.
- Make the code in the Person class that used to raise the event call the OnAddressChanged method instead.
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;
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
In the variable declaration
Action processor
the variable processor represents?
Methods that take Order as object and return void
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
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
Describe delegate variables
- A struct or class can contain fields that are delegate variables
- You can make an array or list of delegate variables
- You can use addition to combine delegate variables and subtraction to remove a method from a series
How is a delegate defined?
accessModifier delegate returnType delegateName(params)
Name the tools associated with multithreading
TPL (Task Parallel Library)
Parallel class
PLINQ
async and await
What actions can be performed with exceptions?
throw
catch
finally
Define events
Events help to create the
publish-subscribe architecture
Define lambda expression
Shorthand syntax for creating inline anonymous methods
Define delegates
Objects that point to a method and can be used to make methods
Name the jump statements
break continue goto return throw
Name the iteration statements
for
foreach
while
do-while
Name the decision statements
if
switch
? (conditional operator)
?? (null coalescing operator)
In a multithreaded environment, it is important to manage synchronization of shared data using which tool?
lock statment
You are creating a custom exception called LogonFailedException.
Which constructors should you add at minimum?
LogonFailedException(); //default
LogonFailedException(string);
LogonFailedException(string, exception);
What keyword is used to raise an exception?
By using the throw keyword
How can you specify code to run whether or not an exception occurs?
with the finally block
How are exceptions typically caught in the .NET framework?
using the try..catch block
Suppose the variable Note is declared by the statement Action Note.
Correctly initialize Note to an expression lambda.
Note = () => MessageBox.Show(“Hi”);
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;
Suppose F is declared by the statement
Func F
Correctly initialize F to an anonymous method
F = delegate(float x)
{
return x* x;
}
In the variable declaration
Func processor;
The variable processor represents?
A method that takes no parameters and returns and Order object
The process of converting a boxed value back to it’s original value is known as ?
unboxing
How are values displayed at a very high level?
Through standard formatting strings
Define narrowing conversion
A data type conversion where the destination type cannot hold all possible values of the source.
Requires an explicit conversion
What is interoperability
Interoperability enables managed code to use classes provided by unmanaged code not under control of CLR
Define the intern pool
A table maintained by the CLR that contains a reference to every unique string used by the program
What type of conversion occurs when a program automatically converts a value from one datatype to another
implicit
Define immutable
A data type is immutable if its value cannot be changed after creation
What do you create to build formats that are not provided by standard formatting strings?
custom formatting strings
Describe an explicit conversion
Using a cast or method to explicitly tell a program how to convert a value from one type to another
What format item used by string.Format indicates how an argument should be formatted?
The composit format
{
index[length][:formatString]
}
What is the CLR?
Common Language Runtime
Manages execution of C# and other .NET programs
What is the process of converting a value type such as a bool or integer into an object or interface?
boxing
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
Why are standard format strings the preferred method?
They are locale-aware
Name two methods that convert values into strings
.ToString()
string.Format()
What classes provide methods for writing and reading characters and lines with an underlying StringBuilder object?
StringWriter
and
StringBuilder
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
You are checking the arguments of your method fro illegal null values. If you encounter a NULL value, which exception do you throw>
ArgumentNullException
Define exceptions
Objects that contain data about the exceptions
How are errors reported in the .NET framework
via exceptions
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
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
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
Define Sentinal
A value used to signal the end for execution in a loop
Define IEnumerable
A code component in C# that supports iterations
Name three generic delegate types defined by the .NET framework
Action
Func
Predicate
Define contravariance
Returns a value from a superclass of the type expected by the delegate
Define covariance
Returns a value from a subclass of the result expected by a delegate
Name the steps to implementing a delegate
- Use the delegate keyword to define delegate type
- Create variables of delegate type
- Set variables equal to methods that match delegates and return type
- Invoke the variable
How to declare a delegate
accessModifier delegate returnType DelegateName();
ex
private delegate int FunctionDelegate(float x);
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
Define Action delegates
A method that returns void and accepts between 0 and 18 parameters
Define Func delegates
A method that returns a value and accepts between 0 and 18 parameters
Provide example of replacing custom delegate with action delegate
private delegate void FunctionDelegate(param)
private FunctionDelegate FunctionParamMethod;
replace with:
private Action FunctionParamMethod;
Provide example of replacing custom delegate with Func delegate
private delegate datatype FunctionDelegate(param)
private FunctionDelegate FunctionParamMethod;
replace with:
private Func FunctionParamMethod;
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
What kind of result is returned in the condition part of an if statement?
bool
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?
&&
You want to declare an integer variable called myVar and assign it to the value 0.
How can you accomplish this?
int myVar = 0;
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 }
What is the purpose of the break in a switch statement?
It causes the code to exit the switch statement
What are the four main repetition structures in C#?
for
foreach
while
do-while
How many times will this loop execute?
int value = 0; do { Console.WriteLine(value); }while(value > 10);
Once
A data type conversion where the destination type can hold all values in the source type is known as ?
Widening conversion
What encoding is used by the .NET framework
UTF-16, 16 bits per character
Define unicode
A standard for encoding characters used by scripts in various locales around the world
What pool holds an instance of every unique string?
The intern pool
String values do not change, they are referred to as ?
immutable
What is a dynamic type
A static type that is not evaluated until runtime
When does unboxing occur?
When converting a reference type to a value type
How does boxing occur?
When converting a value type to a reference type
What class is used to convert data to and from an array of bytes?
System.BitConverter
Name the methods in System.Convert
ToBoolean, ToDouble, ToSingle, ToByte, toInt16, ToString, ToChar, ToInt32, ToInt16, ToDateTime, ToInt64, TUInt32, ToDecimal, ToSByte, ToUInt64
What class provides methods that convert from one type to another?
System.Convert
Name some common styles from System.Globalization.NumberStyles
Integer HexNumber Number Float Currency Any
What enumeration allows Parse and TryParse to understand special symbols?
System.Globalization.NumberStyles
What method can be used to parse text and see if ther is an error?
TryParse()
How is text parsed into values?
using the Parse() method
What is the purpose of the as operator?
To convert an object into a compatible type or NULL if compatibility doesn’t exist.
What is the purpose of the is operator?
To determine if a variable is compatible with a specific type
How are floating point operations checked for overflow or underflow?
By checking the Infinity and/or NegativeInfinity properties
How are integer overflows captured?
Using the checked block
or
Advanced Builds Setting Dialog
Yes or No
Do explicit conversions require a cast operator?
Yes
Yes or No
Do implicit conversions require a cast operator?
No
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
Which statement can be used to capture integer overflow or underflow errors?
checked
Can the string class space method be used to create a string containing 10 spaces?
No
Name three common string methods
IndexOf
StartsWith
Trim
(ther are others)
If Employee inherits from Person and Manager inherits from Employee then assign a Person to an Employee type.
Person alex = new Employee();
The statement object obj=72 is an example of?
boxing
What is the best way to store an integer value typed by the user in a variable?
TryParse
If i is an int and l is a long
then i = (int) l
is what ype of conversion?
narrowing conversion
Generate a string containing the text “Vend, Vidi, Vici”
String.Format(“{0}, {1},{2}”, “Vend”, “Vidi”, “Vici”);
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”));
Name the characteristics of narrowing conversions
The source and destination must be compatible
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
Why are properties valuable?
To perform data validations on incoming and outgoing data values
What operations can be performed on properties?
read/write
read only
write only
What is the purpose of properties?
To present the public interface to your class
In encapsulation, how is data exposed?
Through properties
In encapsulation what access modifier is specified for member variables?
private
What is the purpose of encapsulation?
Functionality and data are enclosed as part of the class
What is another name for data hiding?
encapsulation
What enables you to pass arguments to a method in order other than specified in the message signature?
named parameters
What allows for giving parameters in a method a name?
named parameters
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
When is a default value used?
If none is passed by caller
How are optional parameters defined?
By including a default value
Name the type of parameters that enable you to choose the parameters required in a method
optional parameters
What type of classes are overridden?
Virtual and abstract methods in base classes
What type of method provides the means to change method behavior in a derived class?
overriden methods
What is the purpose of extension methods?
To extend existing lasses by adding methods without recompiling
Where are extension methods applied?
To your own types or existing types in .NET
What is the purpose of overridden methods?
To hide the implementation of a method of the same name in the base class
Where are abstract methods defined?
Abstract methods can only be defined in abstract classes
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
What area is used by the .NET compiler to store reference type variables?
heap
Variables that store the characteristics data for a class are referred to as?
fields
The object that listens for an event to be raised is?
The event subscriber
The object that raises the event for the listener or subscriber is the ?
event publisher
A distinct type consisting of a set of named constants is known as an ?
enumeration
The hiding of details around the implementation of an object so there are no external dependencies on the particular implementation?
encapsulation
Components in code that are used to store data within a program are referred to as?
data structures
What class methods are executed when an object of a given type is created?
constructors
What are coding components that enable you to create custom types to group together characteristics, mehtods and events
classes
What is used to encapsulate data and functionality into one unit of code
class files
What methods are used to access hidden number variables?
accessor methods
When can an abstract modifier be used?
With classes, methods, properties, indexers and events
When is an abstract modifier used?
To indicate that a class is intended to be only a base class of other classes
What technique is used to define methods without specifying the types for parameters at definition stage?
generic types
What is the purpose of the generic type?
Enables type-safe coding
Increase performance due to reduction in conversions, boxing/unboxing.
What types are used as a placeholder at define stage that is replaced by type during instantiation?
generic types
How are indexed properties accessed?
Using an index in the same manner as arrays
What properties allow array like access to group of items?
idexers (indexed properties)
What are instance fields?
fields related to a specific instance. Values are not shared among objects of the same class.
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
Define properties
Members that provide a flexible mechanixm to read, write or compute the values of private fields.
When is the override access method used?
To extend or modify the abstract or virtual implementation of an inherited method, property, indexer or event.
What is the purpose of the modifier?
Modify declarations of types and type members
What is used to provide functionality for a class?
method
What is a memory address?
An addressable location in computer memory used to store and retrieve values
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
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
An area of memory used by the .NET compiler to store value types during program execution is known as the?
Stack
Methods with identical names for procedures that operate on different data types are referred to as ?
overloaded methods
The unique identifying components of a method, such as return type, name and parameter is known as it’s?
signature
class files or other objects represented as references to the actual data (memory address) are referred to as ?
reference types
In entity framework, which class is responsible for maintaining the bridge between a database engine and C# code?
DbContext
Which method is used to return a specific number of objects from a quuery result?
Take()
Which of collection types is used to retrieve data in a Last-In, Last-Out (LIFO) way?
Stack
What keyworkd is used to filter a query?
Where()
Which extension method is used to join two queries?
join()
Suppose you’re writing a method that retrieves the data from an MS Access 2013 database. The method must meet the following requirements;
- Be read-only
- Be able to use the data before the entire data set is retrieved
- 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
Suppose you have the following code segment:
- ArrayList arrays = new ArrayList();
- int i = 10 ;
- int j;
- arrays.Add(i);
- 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];
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))
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);
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));
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
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
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
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
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();
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]; } }
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)); }
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);
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
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();
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();
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();
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);
}
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); } }
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;
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
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
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
You need to validate an XML file. What would you use? A) XSD B) RegEx C) StringBuilder D) JavaScriptSerializer
A) XSD
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
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
Which class should preferably be used for tracing in Release Mode? A) Debug B) Trace C) TraceSource D) All of the above
C) TraceSource
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
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();
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
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
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
The application needs to encrypt highly sensitive data. Which algorithm should you use? A) DES B) Aes C) TripleDES D) RC2
B) Aes
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;
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}”
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
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
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; }
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);
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”);
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
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
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
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
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
Which statement is used to remove the unnecessary resources automatically? A) using B) switch C) Uncheck D) Check
A) using
Which class is necessary to inherit while creating a custom attribute? A) Exception B) Attribute C) Serializable D) IEnumerable
B) Attribute
Which of the following interfaces is used to manage an unmanaged resource? A) IUnkown B) IEnumerable C) IComparable D) IDisposable
D) IDisposable
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
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
Which keyword is used to check or compare one type to another? A) as B) is C) out D) in
B) is
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 } }
What should you use to encapsulate an array object? A) Indexer B) Property C) Event D) Private array
A) Indexer
Which of the following keywords is used for a dynamic variable? A) var B) dynamic C) const D) static
B) dynamic
Which of the following methods of assembly is used to get all types? A) GetTypes() B) GetType() C) ToTypeList() D) Types()
A) GetTypes()
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()
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);
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.
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()
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);
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;
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
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();
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 { }
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() { ... }
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;
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))
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);
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();
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
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);
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
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);
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);
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) { ... }
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 () => { … };
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
Which of the following collections is a thread-safe? A) Dictionary B) Stack C) ConcurrentDictionary D) Queue
C) ConcurrentDictionary
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
Foreach loop can only run on: A) anything B) collection C) const values D) static values
B) collection
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
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()
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()
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()
When handling an exception, which block is useful to release resources? A) try B) catch C) finally D) lock
C) finally
Which keyword is used to prevent a class from inheriting? A) sealed B) lock C) const D) static
A) sealed
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
Which of the following loops is faster? A) for B) do C) Parallel.for D) foreach
C) Parallel.for
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;
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;
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 += ()=>{..};
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;
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
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
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() ;
Which class should you preferably use for tracing in Release Mode? A) Debug B) Trace C) TraceSource D) All of the above
C) TraceSource
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
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
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
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();
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
The application needs to encrypt highly sensitive data. Which algorithm should you use? A) DES B) Aes C) TripleDES D) RC2
B) Aes
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
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
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
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
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();
}
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();
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
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