Upwork Test Answers: Get all the correct answers of most recent and possible Upwork Tests A to Z (Updated on Jan, 2016)
Cover Letter Templates: These cover letter samples are not only for Upwork job, but also you will have some idea about your real life job
 
Freelance Profile Overviews: Different Profile samples and overviews of experts, advanced and intermediate level freelancers
For Newbie of Upwork: Upwork Help - How to apply for a job in Upwork with 10 most important articles about Upwork

A to Z View - All Upwork Test Answers

C# Test Answers

Here you will find all Upwork C# Test Answers of Upwork .Net Technologies category, please press Ctrl + F to find your desired answers of the test questions.
--------------------------------------------------------------------------------------------------------------------------
1. Which of the following define the rules for .NET Languages?
 Answers: • CLS or • CLR

 2. Suppose there is a List of type Person with a property of LastName(string) and PopulateList is a function which returns a Generic List of type Person:
 List<Person> people = PopulateList();

 What does the statement below do?
 people.Sort((x, y) => string.Compare(x.LastName, y.LastName));
 Answers: • It will return a newly created sorted List.

 3. Which of the following will correctly remove duplicates from a List<T>?
 Answers: • List<T> withDupes = LoadSomeData(); List<T> noDupes = withDupes.Distinct().ToList();

 4. Is it possible to define custom Exception classes in C#?
 Answers: • Yes, but they have to be derived from System.Exception class

 5. Which type of class members are associated with the class itself rather than the objects of the class?
 Answers: • Static

 6. What is the syntax required to load and use a normal unmanaged windows DLL (e.g. kernel32.DLL) in a managed .NET C# code?
 Answers: • [DllImport(''kernel32'', SetLastError=true)]

 7. What is the output of the following code?

 class Test
 {
 static void Main() {
 string myString = “1 2 3 4 5”
 myString = Regex.Replace(myString, @"\s+", " ");
 System.Console.WriteLine(myString);
 }
 Answers: • 1 2 3 4 5

 8. Which of the following will block the current thread for a specified number of milliseconds?
 Answers: • System.Threading.Thread.Sleep(50);

 9. What is the problem with the following function, which is supposed to convert a Stream into byte array?
 public static byte[] ReadFully(Stream input)
 {
 using (MemoryStream ms = new MemoryStream())
 {
 input.CopyTo(ms);
 return ms.ToArray();
 }
 }
 Answers: • It will work only in .NET Framework 4 or above, as the CopyTo function of the memory stream is available only in .NET Framework 4 or later versions.

 10. Which of the following functions are used to wait for a thread to terminate?
 Answers: • Join()


 11. _____________ helped overcome the DLL conflict faced by the C# language versions prior to .NET.
 Answers: • GAC

 12. What is the benefit of using a finally{} block with a try-catch statement in C#?
 Answers: • The finally block is always executed before the thread is aborted.

 13. In which of the following namespaces is the Assembly class defined?
 Answers: • System.Reflection

 14. Which of the following statements is true regarding predicate delegates in C#?
 Answers: • Predicate delegates are references to functions that return true or false.

 15. Working with a list of Employees:
 List<Employee> lstEmployees = new List<Employee>
 {
 new Employee{Name="Harry",Age=15},
 new Employee{Name="Peter",Age=22},
 new Employee{Name="John",Age=45},
 new Employee{Name="Harry",Age=15},
 new Employee{Name="Peter",Age=22},
 new Employee{Name="John",Age=45},

 };

 It is required to filter out employees having distinct names.
 Which one of the following options cannot be used?
 Answers: • public class Employee:IEqualityComparer<Employee> { public int Age { get; set; } public string Name { get; set; } #region IEqualityComparer<Employee> Members public bool Equals(Employee x, Employee y) { return x.Name.Equals(y.Name); } public int GetHashCode(Employee obj) { return obj.Name.GetHashCode(); } #endregion } List<Employee> distinctEmployeesByName = lstEmployees.Distinct().ToList();

 16. What are the benefits of using the ExpandoObject class over a using dictionary?
 Answers: • ExpandoObject can help in creating complex hierarchical objects. ExpandoObject implements the INotifyPropertyChanged interface, which gives more control over properties than a dictionary.

 17. What will be the output of the following Main program in a C# console application (Assume required namespaces are included):

 static void Main(string[] args)
 {
 int @int = 15;
 Console.WriteLine(@int);
 Console.ReadLine();
 }
 Answers: • 15

 18. What is the purpose of the catch block in the following code?

 try {
 // Code that might throw exceptions of different types
 }

 catch {
 // Code goes here
 }
 Answers: • This catch block can be the last one in a series of catch blocks to handle any exception which is not handled by the preceding catch blocks, each of which handles an exception of a particular type.

 19. Which of the following is true about friend functions in C#?
 Answers: • Friend functions are not available in C#.

 20. Which of the following statements is true about the code below?

 string[] lines = theText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
 Answers: • It splits the string variable on a system line break, while preserving the empty lines.

 21. Consider the following code:

 string s1 = "Old Value";
 string s2 = s1;
 s1 = "New Value";
 Console.WriteLine(s2);

 What will be the output printed, and why?
 Answers: • "Old Value", because string is a reference type which is treated as a special case by the assignment operator.

 22. What will be the output if in a WinForms application, the following code is executed in the Load event of a form? Assume this form has lblMessage as a Label Control.

 private void Form1_Load(object sender, EventArgs e)
 {
 try
 {
 ThreadPool.QueueUserWorkItem(ShowMessage,null);
 }
 catch (Exception ex)
 {
 }
 }

 private void ShowMessage(object obj)
 {
 try
 {
 lblMessage.Text = "Hello from Thread Pool";
 }
 catch (Exception ex)
 {
 }
 }
 Answers: • An InvalidOperationException will be thrown for the function ShowMessage as the UI can be updated only from the UI thread.

 23. What are Satellite assemblies in C# .NET?
 Answers: • Assemblies that contain only resource information and no code

 24. Where does a C# assembly store the information regarding the other external dependencies, such as satellite assemblies, global assemblies etc, and their versions so that they can be loaded correctly when the assembly is executed?
 Answers: • In the manifest of the assembly

 25. Which of the following will output the string below?
 "\t\t\t\t\t"
 Answers: • private string Tabs(uint numTabs) { String output = new String('\t', numTabs); return output; }

 26. Complete the following sentence:

 In C#, exception handling should be used...
 Answers: • to handle the occurrence of unusual or unanticipated program events

 27. The global assembly cache:
 Answers: • Can store two DLL files with the same name, but different versions

 28. Which statements will give the path where the executing assembly is currently located?
 Answers: • System.Reflection.Assembly.GetExecutingAssembly().Location;

 29. In C#, can global functions that are not associated with a particular class be defined?
 Answers: • No

 30. Which of the following code snippets will call a generic method when the type parameter is not known at compile time?
 Answers: • Action<> GenMethod = GenericMethod< myType >; MethodInfo method = this.GetType().GetMethod("GenericMethod"); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null);

 31. Which of the following is true for CLR?
 Answers: • All of these.

 32. In the sample code given below, which of the data members are accessible from class Y?

 class X {
 private int i;
 protected float f;
 public char c;
 }

 class Y : X { }
 Answers: • c

 33. If i == 0, why is (i += i++) == 0 in C#?
 Answers: • // source code i += i++; //abstract syntax tree += / \ i ++ (post) \ i First, i++ returns 0. Then i is incremented by 1. Lastly i is set to the initial value of i which is 0 plus the value i++ returned, which is zero too. 0 + 0 = 0.

 34. Performance-wise, which of the following is the most efficient way to calculate the sum of integers stored in an object array?
 Answers: • int FindSum (object[] values) { int sum = values.OfType<int>().Sum(); return sum; }

 35. Consider the following code block:

 public class Person
 {
 public string GetAge()
 {
 lock (this)
 {
 // Code to get Age of this person object.
 }
 }
 }

 Which of the following statements is true?
 Answers: • lock(this) can be problematic if the instance can be accessed publicly, because code beyond one's control may lock on the object as well. This could create deadlock situations where two or more threads wait for the release of the same object.

 36. The ___________ namespace is not defined in the .NET class library.
 Answers: • System.Thread

 37. Which of the following is true about constructors and member functions?
 Answers: • A member function can return values, but a constructor cannot.

 38. Which of the following language code is not 'managed' by default in .NET framework?
 Answers: • C++

 39. There is a class that has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented. To increment this field, three thread-safe approaches are mentioned below:

 A) lock(this.locker) this.counter++;
 B) Interlocked.Increment(ref this.counter);
 C) Change the access modifier of counter to public volatile

 Which statement is incorrect with regards to these approaches?
 Answers: • B is the best approach as it effectively does the read, increment, and write in 'one hit' which can't be interrupted.

 40. What will happen if the following code is compiled in .NET 4 or above (Assume required namespaces are included)?

 public class var { }
 public class main
 {
 public static void main(string[] args)
 {
 var testVar = new var();
 }
 }
 Answers: • This code will compile, as var is merely a contextual keyword and it is used to provide a specific meaning in the code, so it will cause no problems.

 41. Which object oriented term is related to protecting data from access by unauthorized functions?
 Answers: • Data hiding

 42. One of the ternary operators provided in C# is:
 Answers: • ?:

 43. What type of code is written to avail the services provided by Common Language Runtime?
 Answers: • Managed Code

 44. Asynchronous execution is supported in ADO.NET 2.0 for?
 Answers: • All of these

 45. The .NET Framework consists of:
 Answers: • The Common Language Runtime and a set of class libraries

 46. An enum is defined in a program as follows:
 [Flags]
 public enum Permissions
 {
 None = 0,
 Read = 1,
 Write = 2,
 Delete = 4
 }

 What will be the output of the following Main program (which has access to the enum defined above) in this C# console application (Assume required namespaces are included) :

 static void Main(string[] args)
 {
 var permissions = Permissions.Read | Permissions.Write;
 if ((permissions & Permissions.Write) == Permissions.Write)
 {
 Console.WriteLine("Write");
 }
 if ((permissions & Permissions.Delete) == Permissions.Delete)
 {
 Console.WriteLine("Delete");
 }
 if ((permissions & Permissions.Read) == Permissions.Read)
 {
 Console.WriteLine("Read");
 }
 Console.ReadLine();
 }
 Answers: • Write Read

 47. Which of the following keywords prevents a class from being overridden further?
 Answers: • sealed

 48. Suppose a class is declared as a protected internal:
 protected internal class A
 {
 }

 Which statement is correct with regards to its accessibility?
 Answers: • This class can only be accessed by code which is in the derived class (i.e. classes derived from Class A) and which are in the same assembly.

 49. Which of the following is the correct way to randomize a generic list of 75 numbers using C#?
 Answers: • Random random = new Random(); List<object> products= GetProducts(); products.OrderBy(product => random.Next(products.Count));

 50. What will be the value of the result variable after these two statements?


 int num1 = 10, num2 = 9;

 int result = num1 & num2;
 Answers: • 8

 51. What is the output of the following code:

 class CCheck {

 public static void Main() {
 string str = @"E:\\RIL\\test.cs";
 Console.WriteLine(str);
 }
 }
 Answers: • E:\\RIL\\test.cs

 52. What is the issue with the following function?

 public string GetName(int iValue)
 {
 string sValue = "0";
 switch (iValue)
 {
 case 1:
 sValue = iValue.ToString();
 case 2:
 sValue = iValue.ToString();
 break;
 default:
 sValue = "-1";
 break;
 }
 return sValue;
 }
 Answers: • The code will not compile as there is no break statement in case 1.

 53. What will be the output of the following Main program in a C# console application (Assume required namespaces are included):

 static void Main(string[] args)
 {
 for (int i = 0; i < 1; i++)
 {
 Console.WriteLine("No Error");
 }
 int A = i;
 Console.ReadLine();
 }
 Answers: • This program will throw a compilation error, "The name 'i' does not exist in the current context".

 54. What is the difference between int and System.Int32 CLR types?
 Answers: • int is just an alias for System.Int32, there is no difference between them.

 55. What will be the return value if the function fn is called with a value of 50 for the parameter var?

 public int fn(int var)
 {
 int retvar = var - (var / 10 * 5);
 return retvar;
 }
 Answers: • 25

 56. Which of the following code snippets converts an IEnumerable<string> into a string containing comma separated values?
 Answers: • public static string ConvertToString(IEnumerable<T> source) { return string.Join(",",source.ToArray()); }

 57. Which of the following is true regarding a null and an empty collection in C#?
 Answers: • An empty collection is an object while the null keyword is a literal.

 58. Which of the following exceptions cannot be thrown by the Delete() function of the FileInfo class (ie. FileInfo.Delete())?
 Answers: • InvalidOperationException

 59. Which of the following statements are true regarding the ref and out parameters in C#?
 Answers: • The ref parameter is considered initially assigned by the callee. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.

 60. What is the difference between the String and StringBuilder class objects with respect to mutability?
 Answers: • String objects are immutable, while StringBuilder objects are mutable.

 61. Which of the following code samples will create a comma separated list from IList<string> or IEnumerable<string>?
 Answers: • List<string> ls = new List<string>(); ls.Add("one"); ls.Add("two"); string type = string.Join(",", ls.ToArray());

 62. What is the advantage of using IList<T> over List<T>?
 Answers: • Using IList<T> rather than List<T> allows the code to be more flexible. It can replace the implementation with any collection that implements IList<T> without breaking any calling code.

 63. How can a single instance application be created in C#?
 Answers: • System.Threading.Mutex can be used to ensure that only one instance of a program can run at a time.

 64. Which of the following code samples will execute a command-line program in C# and return its STD OUT results?
 Answers: • System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("program_to_call.exe"); psi.RedirectStandardOutput = true; psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; psi.UseShellExecute = false; System.Diagnostics.Process proc System.Diagnostics.Process.Start(psi);; System.IO.StreamReader myOutput = proc.StandardOutput; proc.WaitForExit(2000); if (proc.HasExited) { string output = myOutput.ReadToEnd(); }


 65. What is an Action delegate?
 Answers: • An Action is a delegate to a method, that takes zero, one or more input parameters, but does not return anything.

 66. What is the difference between Expression<Func<T>> and Func<T>?
 Answers: • Func<T> denotes a delegate, while Expression<Func<T>> denotes a tree data structure for a lambda expression.

 67. Which of the following statements is true about IEnumerable<T>?
 Answers: • IEnumerable<T> supports a Count() extension.

 68. Which of the following statements is true about the System.Environment.NewLine property?
 Answers: • It's a string containing "\r\n" for non-Unix platforms.

 69. An Interface represents which kind of relationship?
 Answers: • CAN DO

 70. Why is it a bad practice to use iteration variables in lambda expressions?
 Answers: • Iteration variables can cause problems with accessing a modified closure.

 71. Which of the following code samples will check if a file is in use?
 Answers: • protected virtual bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { return true; } finally { if (stream != null) stream.Close(); } return false; }

 72. Which of the following statements is true regarding the code samples below?

 A:
 try {
 // code goes here
 } catch (Exception e) {
 throw e;
 }

 B:
 try {
 // code goes here
 } catch (Exception e) {
 throw;
 }
 Answers: • A will lose the call stack trace information. B will preserve the call stack trace information.

 73. Which of the following is the correct way to implement deep copying of an object in C#?
 Answers: • By using the System.Runtime.Serialization.Formatters.Binary.BinaryFormatter class.

 74. What will be the output of the following Main program in a C# console application (Assume required namespaces are included)?

 static void Main(string[] args)
 {
 string Invalid = "$am$it$";
 string sResult = Invalid.Trim(new char[]{'$'});
 Console.WriteLine(sResult);
 Console.ReadLine();
 }
 Answers: • am$it

 75. Which of the following is the correct way to perform a LINQ query on a DataTable object?
 Answers: • var results = from myRow in myDataTable.AsEnumerable() where myRow.Field<int>("RowNo") == 1 select new { IID= myRow.Field<int>("IID"), Date = myRow.Field<DateTime>("Date"), };

 76. What is the purpose of the vshost.exe file in Visual Studio?
 Answers: • It is used to improve the performance of the Visual Studio debugger.

 77. Which of the following code snippets for catch shows a better way of handling an exception?

 1.
 catch (Exception exc)
 {
 throw exc;
 }


 2.
 catch (Exception exc)
 {
 throw;
 }
 Answers: • 2 is better as it maintains the call stack.

 78. What will be the value of result after these two statements?

 int num1 = 10, num2 = 9;
 int result = num1 ^ num2;
 Answers: • 3

 79. What will be the output of the following Main program in a C# console application (Assume required namespaces are included)?
 static void Main(string[] args)
 {
 string sPrint = String.Format("{{ My name is bond. }}");
 Console.WriteLine(sPrint);
 Console.ReadLine();
 }
 Answers: • It will throw a compilation error.

 80. What is the difference between data types "System.String" and "string" in C#?
 Answers: • There is no difference,string is just an alias of the System.String data type.

 81. Which of the following is the correct code to close all references to the com objects below?

 Workbooks books = excel.WorkBooks;
 Workbook book = books[1];
 Sheets sheets = book.WorkSheets;
 Worksheet ws = sheets[1];
 Answers: • Marshal.ReleaseComObject(sheets); Marshal.ReleaseComObject(books);

 82. Which of the following is the correct way to sort a C# dictionary by value?
 Answers: • foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value)) { // do something with item.Key and item.Value }

========================================================================

C# Test Answers - 2014 & 2015

1. Which of the following define the rules for .NET Languages?
 Answers: • CLS --- or --- • CLR


 2. Which of the following will correctly remove duplicates from a List<T>?
 Answers: • List<T> withDupes = LoadSomeData(); List<T> noDupes = withDupes.Distinct().ToList();


 3. Which type of class members are associated with the class itself rather than the objects of the class?
 Answers: • Static


 4. Which of the following will block the current thread for a specified number of milliseconds?
 Answers: • System.Threading.Thread.Sleep(50);


 5. Which of the following statements is true regarding predicate delegates in C#?
 Answers: • Predicate delegates are references to functions that return true or false.


 6. What are the benefits of using the ExpandoObject class over a using dictionary?
 Answers: • ExpandoObject can help in creating complex hierarchical objects. ExpandoObject implements the INotifyPropertyChanged interface, which gives more control over properties than a dictionary.


 7. What are Satellite assemblies in C# .NET?
 Answers: • Assemblies that contain only resource information and no code


 8. Where does a C# assembly store the information regarding the other external dependencies, such as satellite assemblies, global assemblies etc, and their versions so that they can be loaded correctly when the assembly is executed?
 Answers: • In the manifest of the assembly


 9. Which of the following will output the string below?
 "\t\t\t\t\t"
 Answers: • private string Tabs(uint numTabs) { String output = new String('\t', numTabs); return output; }


 10. The global assembly cache:
 Answers: • Can store two DLL files with the same name, but different versions


 11. Which statements will give the path where the executing assembly is currently located?
 Answers: • System.Reflection.Assembly.GetExecutingAssembly().Location;


 12. There is a class that has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented. To increment this field, three thread-safe approaches are mentioned below:

 A) lock(this.locker) this.counter++;
 B) Interlocked.Increment(ref this.counter);
 C) Change the access modifier of counter to public volatile

 Which statement is incorrect with regards to these approaches?
 Answers: • B is the best approach as it effectively does the read, increment, and write in 'one hit' which can't be interrupted.


 13. What will happen if the following code is compiled in .NET 4 or above (Assume required namespaces are included)?

 public class var { }
 public class main
 {
 public static void main(string[] args)
 {
 var testVar = new var();
 }
 }
 Answers: • This code will compile, as var is merely a contextual keyword and it is used to provide a specific meaning in the code, so it will cause no problems.


 14. Which object oriented term is related to protecting data from access by unauthorized functions?
 Answers: • Data hiding


 15. The .NET Framework consists of:
 Answers: • The Common Language Runtime and a set of class libraries


 16. What will be the value of the result variable after these two statements?


 int num1 = 10, num2 = 9;

 int result = num1 & num2;
 Answers: • 8


 17. Which of the following code snippets converts an IEnumerable<string> into a string containing comma separated values?
 Answers: • public static string ConvertToString(IEnumerable<T> source) { return string.Join(",",source.ToArray()); }


 18. Which of the following code samples will create a comma separated list from IList<string> or IEnumerable<string>?
 Answers: • List<string> ls = new List<string>(); ls.Add("one"); ls.Add("two"); string type = string.Join(",", ls.ToArray());


 19. What is the advantage of using IList<T> over List<T>?
 Answers: • Using IList<T> rather than List<T> allows the code to be more flexible. It can replace the implementation with any collection that implements IList<T> without breaking any calling code.


 20. Which of the following code samples will execute a command-line program in C# and return its STD OUT results?
 Answers: • System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("program_to_call.exe"); psi.RedirectStandardOutput = true; psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; psi.UseShellExecute = false; System.Diagnostics.Process proc System.Diagnostics.Process.Start(psi);; System.IO.StreamReader myOutput = proc.StandardOutput; proc.WaitForExit(2000); if (proc.HasExited) { string output = myOutput.ReadToEnd(); }



 21. What is an Action delegate?
 Answers: • An Action is a delegate to a method, that takes zero, one or more input parameters, but does not return anything.


 22. Which of the following code samples will check if a file is in use?
 Answers: • protected virtual bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { return true; } finally { if (stream != null) stream.Close(); } return false; }


 23. Which of the following statements is true regarding the code samples below?

 A:
 try {
 // code goes here
 } catch (Exception e) {
 throw e;
 }

 B:
 try {
 // code goes here
 } catch (Exception e) {
 throw;
 }
 Answers: • A will lose the call stack trace information. B will preserve the call stack trace information.


 24. Suppose there is a List of type Person with a property of LastName(string) and PopulateList is a function which returns a Generic List of type Person:
 List<Person> people = PopulateList();

 What does the statement below do?
 people.Sort((x, y) => string.Compare(x.LastName, y.LastName));
 Answers: • It will return a newly created sorted List.


 25. Is it possible to define custom Exception classes in C#?
 Answers: • Yes, but they have to be derived from System.Exception class


 26. What is the syntax required to load and use a normal unmanaged windows DLL (e.g. kernel32.DLL) in a managed .NET C# code?
 Answers: • [DllImport(''kernel32'', SetLastError=true)]


 27. What is the output of the following code?

 class Test
 {
 static void Main() {
 string myString = “1 2 3 4 5”
 myString = Regex.Replace(myString, @"\s+", " ");
 System.Console.WriteLine(myString);
 }
 Answers: • 1 2 3 4 5


 28. What is the problem with the following function, which is supposed to convert a Stream into byte array?
 public static byte[] ReadFully(Stream input)
 {
 using (MemoryStream ms = new MemoryStream())
 {
 input.CopyTo(ms);
 return ms.ToArray();
 }
 }
 Answers: • It will work only in .NET Framework 4 or above, as the CopyTo function of the memory stream is available only in .NET Framework 4 or later versions.


 29. Which of the following functions are used to wait for a thread to terminate?
 Answers: • Join()


 30. _____________ helped overcome the DLL conflict faced by the C# language versions prior to .NET.
 Answers: • GAC


 31. What is the benefit of using a finally{} block with a try-catch statement in C#?
 Answers: • The finally block is always executed before the thread is aborted.


 32. In which of the following namespaces is the Assembly class defined?
 Answers: • System.Reflection


 33. Working with a list of Employees:
 List<Employee> lstEmployees = new List<Employee>
 {
 new Employee{Name="Harry",Age=15},
 new Employee{Name="Peter",Age=22},
 new Employee{Name="John",Age=45},
 new Employee{Name="Harry",Age=15},
 new Employee{Name="Peter",Age=22},
 new Employee{Name="John",Age=45},

 };

 It is required to filter out employees having distinct names.
 Which one of the following options cannot be used?
 Answers: • public class Employee:IEqualityComparer<Employee> { public int Age { get; set; } public string Name { get; set; } #region IEqualityComparer<Employee> Members public bool Equals(Employee x, Employee y) { return x.Name.Equals(y.Name); } public int GetHashCode(Employee obj) { return obj.Name.GetHashCode(); } #endregion } List<Employee> distinctEmployeesByName = lstEmployees.Distinct().ToList();



 34. What will be the output of the following Main program in a C# console application (Assume required namespaces are included):

 static void Main(string[] args)
 {
 int @int = 15;
 Console.WriteLine(@int);
 Console.ReadLine();
 }
 Answers: • 15


 35. What is the purpose of the catch block in the following code?

 try {
 // Code that might throw exceptions of different types
 }

 catch {
 // Code goes here
 }
 Answers: • This catch block can be the last one in a series of catch blocks to handle any exception which is not handled by the preceding catch blocks, each of which handles an exception of a particular type.


 36. Which of the following is true about friend functions in C#?
 Answers: • Friend functions are not available in C#.


 37. Which of the following statements is true about the code below?

 string[] lines = theText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
 Answers: • It splits the string variable on a system line break, while preserving the empty lines.


 38. Consider the following code:

 string s1 = "Old Value";
 string s2 = s1;
 s1 = "New Value";
 Console.WriteLine(s2);

 What will be the output printed, and why?
 Answers: • "Old Value", because string is a reference type which is treated as a special case by the assignment operator.


 39. What will be the output if in a WinForms application, the following code is executed in the Load event of a form? Assume this form has lblMessage as a Label Control.

 private void Form1_Load(object sender, EventArgs e)
 {
 try
 {
 ThreadPool.QueueUserWorkItem(ShowMessage,null);
 }
 catch (Exception ex)
 {
 }
 }

 private void ShowMessage(object obj)
 {
 try
 {
 lblMessage.Text = "Hello from Thread Pool";
 }
 catch (Exception ex)
 {
 }
 }
 Answers: • An InvalidOperationException will be thrown for the function ShowMessage as the UI can be updated only from the UI thread.


 40. Complete the following sentence:

 In C#, exception handling should be used...
 Answers: • to handle the occurrence of unusual or unanticipated program events


 41. In C#, can global functions that are not associated with a particular class be defined?
 Answers: • No


 42. Which of the following code snippets will call a generic method when the type parameter is not known at compile time?
 Answers: • Action<> GenMethod = GenericMethod< myType >; MethodInfo method = this.GetType().GetMethod("GenericMethod"); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null);


 43. Which of the following is true for CLR?
 Answers: • All of these.


 44. In the sample code given below, which of the data members are accessible from class Y?

 class X {
 private int i;
 protected float f;
 public char c;
 }

 class Y : X { }
 Answers: • c


 45. If i == 0, why is (i += i++) == 0 in C#?
 Answers: • // source code i += i++; //abstract syntax tree += / \ i ++ (post) \ i First, i++ returns 0. Then i is incremented by 1. Lastly i is set to the initial value of i which is 0 plus the value i++ returned, which is zero too. 0 + 0 = 0.


 46. Performance-wise, which of the following is the most efficient way to calculate the sum of integers stored in an object array?
 Answers: • int FindSum (object[] values) { int sum = values.OfType<int>().Sum(); return sum; }


 47. Consider the following code block:

 public class Person
 {
 public string GetAge()
 {
 lock (this)
 {
 // Code to get Age of this person object.
 }
 }
 }

 Which of the following statements is true?
 Answers: • lock(this) can be problematic if the instance can be accessed publicly, because code beyond one's control may lock on the object as well. This could create deadlock situations where two or more threads wait for the release of the same object.


 48. The ___________ namespace is not defined in the .NET class library.
 Answers: • System.Thread


 49. Which of the following is true about constructors and member functions?
 Answers: • A member function can return values, but a constructor cannot.


 50. Which of the following language code is not 'managed' by default in .NET framework?
 Answers: • C++


 51. One of the ternary operators provided in C# is:
 Answers: • ?:


 52. What type of code is written to avail the services provided by Common Language Runtime?
 Answers: • Managed Code


 53. Asynchronous execution is supported in ADO.NET 2.0 for?
 Answers: • All of these


 54. An enum is defined in a program as follows:
 [Flags]
 public enum Permissions
 {
 None = 0,
 Read = 1,
 Write = 2,
 Delete = 4
 }

 What will be the output of the following Main program (which has access to the enum defined above) in this C# console application (Assume required namespaces are included) :

 static void Main(string[] args)
 {
 var permissions = Permissions.Read | Permissions.Write;
 if ((permissions & Permissions.Write) == Permissions.Write)
 {
 Console.WriteLine("Write");
 }
 if ((permissions & Permissions.Delete) == Permissions.Delete)
 {
 Console.WriteLine("Delete");
 }
 if ((permissions & Permissions.Read) == Permissions.Read)
 {
 Console.WriteLine("Read");
 }
 Console.ReadLine();
 }
 Answers: • Write Read


 55. Which of the following keywords prevents a class from being overridden further?
 Answers: • sealed


 56. Suppose a class is declared as a protected internal:
 protected internal class A
 {
 }

 Which statement is correct with regards to its accessibility?
 Answers: • This class can only be accessed by code which is in the derived class (i.e. classes derived from Class A) and which are in the same assembly.


 57. Which of the following is the correct way to randomize a generic list of 75 numbers using C#?
 Answers: • Random random = new Random(); List<object> products= GetProducts(); products.OrderBy(product => random.Next(products.Count));


 58. What is the output of the following code:

 class CCheck {

 public static void Main() {
 string str = @"E:\\RIL\\test.cs";
 Console.WriteLine(str);
 }
 }
 Answers: • E:\\RIL\\test.cs


 59. What is the issue with the following function?

 public string GetName(int iValue)
 {
 string sValue = "0";
 switch (iValue)
 {
 case 1:
 sValue = iValue.ToString();
 case 2:
 sValue = iValue.ToString();
 break;
 default:
 sValue = "-1";
 break;
 }
 return sValue;
 }
 Answers: • The code will not compile as there is no break statement in case 1.


 60. What will be the output of the following Main program in a C# console application (Assume required namespaces are included):

 static void Main(string[] args)
 {
 for (int i = 0; i < 1; i++)
 {
 Console.WriteLine("No Error");
 }
 int A = i;
 Console.ReadLine();
 }
 Answers: • This program will throw a compilation error, "The name 'i' does not exist in the current context".


 61. What is the difference between int and System.Int32 CLR types?
 Answers: • int is just an alias for System.Int32, there is no difference between them.


 62. What will be the return value if the function fn is called with a value of 50 for the parameter var?

 public int fn(int var)
 {
 int retvar = var - (var / 10 * 5);
 return retvar;
 }
 Answers: • 25


 63. Which of the following is true regarding a null and an empty collection in C#?
 Answers: • An empty collection is an object while the null keyword is a literal.


 64. Which of the following exceptions cannot be thrown by the Delete() function of the FileInfo class (ie. FileInfo.Delete())?
 Answers: • InvalidOperationException


 65. Which of the following statements are true regarding the ref and out parameters in C#?
 Answers: • The ref parameter is considered initially assigned by the callee. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.


 66. What is the difference between the String and StringBuilder class objects with respect to mutability?
 Answers: • String objects are immutable, while StringBuilder objects are mutable.


 67. How can a single instance application be created in C#?
 Answers: • System.Threading.Mutex can be used to ensure that only one instance of a program can run at a time.


 68. What is the difference between Expression<Func<T>> and Func<T>?
 Answers: • Func<T> denotes a delegate, while Expression<Func<T>> denotes a tree data structure for a lambda expression.


 69. Which of the following statements is true about IEnumerable<T>?
 Answers: • IEnumerable<T> supports a Count() extension.


 70. Which of the following statements is true about the System.Environment.NewLine property?
 Answers: • It's a string containing "\r\n" for non-Unix platforms.


 71. An Interface represents which kind of relationship?
 Answers: • CAN DO


 72. Why is it a bad practice to use iteration variables in lambda expressions?


 Answers: • Iteration variables can cause problems with accessing a modified closure.


 73. Which of the following is the correct way to implement deep copying of an object in C#?


 Answers: • By using the System.Runtime.Serialization.Formatters.Binary.BinaryFormatter class.


 74. What will be the output of the following Main program in a C# console application (Assume required namespaces are included)?

 static void Main(string[] args)
 {
 string Invalid = "$am$it$";
 string sResult = Invalid.Trim(new char[]{'$'});
 Console.WriteLine(sResult);
 Console.ReadLine();
 }
 Answers: • am$it


 75. Which of the following is the correct way to perform a LINQ query on a DataTable object?


 Answers: • var results = from myRow in myDataTable.AsEnumerable() where myRow.Field<int>("RowNo") == 1 select new { IID= myRow.Field<int>("IID"), Date = myRow.Field<DateTime>("Date"), };
 
 76. What is the purpose of the vshost.exe file in Visual Studio?
 
 Answers: • It is used to improve the performance of the Visual Studio debugger.
 
 77. Which of the following code snippets for catch shows a better way of handling an exception?

 1.
 catch (Exception exc)
 {
 throw exc;
 }


 2.
 catch (Exception exc)
 {
 throw;
 }
 Answers: • 2 is better as it maintains the call stack.