CS 3500 Midterm
Consider this C# code snippet with blanks left to fill in: public delegate BLANK1 NetworkHandler(BLANK2 x); private static void PrintMessage(string m){ Console.WriteLine(m); } static void Main(string[] args){ Network network = new Network(); network.BLANK3; network.StartNetworkListener(); // ... other code } Assume the Network class has the following declaration: public event NetworkHandler MessageArrived; Also assume that StartNetworkListener begins an infinite loop that receives messages over the network, converts them to strings, and then invokes its MessageArrived event with the string received. Fill in the blanks from the code above with exact C# code so that PrintMessage will be used to print the messages received over the network. Do not include any spaces in your answers. BLANK1: BLANK2: (Note that there is a dot in front of BLANK3 and a semicolon after it) BLANK3:
**Check answers Quiz 11
Consider the following C# snippet. string pattern = "I saw ([0-9]|like, tons of) dogs today"; Regex.IsMatch(str, pattern); For which values of str will the IsMatch statement return true? Select all that apply. - "I saw 1 dogs today" - "I saw 15 dogs today" - "When walking earlier, I saw like, tons of dogs today" - "I saw dogs today"
- "I saw 1 dogs today" - "When walking earlier, I saw like, tons of dogs today"
public class Thing{ public int x; } static void Main(string[] args){ Thing t = new Thing(); t.x = 5; Foo(ref t); Console.WriteLine(t.x); } static void Foo(ref Thing t){ t.x++; t = new Thing();t.x = 1; } } - It does not compile due to improper use of the ref keyword - It does not compile due to use of an unassigned value - 5 is printed - 6 is printed - 1 is printed
- 1 is printed
Which of the following C# strings represent a regular expression that only matches all strings containing only a whole US dollar amount that is less than 100, but not negative. A whole US dollar amount is a dollar sign '$' followed by one or more digits, and does not contain any fractional dollars (cents). Leading 0s are allowed up to 2 digits total. Select all that apply. - @"^$[0-9][0-9]?\$" - @"^\$[0-9][0-9]?$" - @"^\$[0-9]+$" - @"^\$[0-9][0-9]$" - @"^\$[0-9]{1,2}$"
- @"^\$[0-9][0-9]?$" - @"^\$[0-9]{1,2}$"
For which of the following classes would it make sense to overload the * operator? Select all that apply. - A 2D matrix class for linear algebra applications - A vector class for physics simulations - A binary search tree class - A server class for networking applications
- A 2D matrix class for linear algebra applications - A vector class for physics simulations
Consider the following C# class public class Thing{ public static bool operator!=(Thing left, Thing right){ if(left != right) return true; else return false; } // other code... } Assume that the == operator has also been overloaded for class Thing. Now consider this Main method and assume class Thing is accessible: static void Main(string[] args){ Thing t1 = ... // some unknown value, possibly null Thing t2 = ... // some unknown value, possibly null Console.WriteLine(t1 != t2); } Note that this code does *not* treat warnings as errors, and there may be null value warnings, but it still compiles. If the "..." are replaced with valid assignments to a Thing variable, which of the following outcomes are possible after executing this program? Select all that apply. - A NullReferenceException is thrown - Either True or False is printed - A StackOverflowException is thrown - The outcome is impossible to know due to undefined behavior
- A StackOverflowException is thrown
Which of the following statements are true about default constructors? Select all that apply. - A default constructor takes 0 parameters - The default constructor is always the one invoked by derived class constructors when constructing polymorphic types - All classes must have a default constructor - Only abstract classes can have a default constructor
- A default constructor takes 0 parameters
Which of the following are true about the out and ref keywords? Select all that apply. - out makes a parameter pass by value and ref makes a parameter pass by reference - A variable passed as an out argument must be initialized before the method call - A variable passed as a ref argument must be initialized before the method call - If a method has an out parameter, that parameter must be assigned to within the method - If a method has a ref parameter, that parameter must be assigned to within the method
- A variable passed as a ref argument must be initialized before the method call - If a method has an out parameter, that parameter must be assigned to within the method
In PS3, you need to determine what type each token is. In order to determine if a token represents a number, you should use: - Double.TryParse - Int32.Parse - Int32.TryParse
- Double.TryParse
Which of the following are true about extension methods? Select all that apply. Hint: write some code and try it out! - They grant access to the private fields of the class they are extending - They grant access to the private methods of the class they are extending - They can only extend static classes - Extension methods must be static - They modify the class being extended
- Extension methods must be static
Lambda expressions, Func and Action should be used: - Whenever possible - they are much faster than the alternatives - For simple expressions or delegate declarations that are just as easy to read as their alternatives - Never - they are poor design
- For simple expressions or delegate declarations that are just as easy to read as their alternatives
To make a class immutable in C#, the class must: Select all that apply. - Be declared with the immutable keyword - Have no methods, other than the constructor, that modify any fields of the class - Be abstract - Be static - Have only const fields
- Have no methods, other than the constructor, that modify any fields of the class
Assume a correct Formula class has been implemented. When trying to instantiate Formula objects in Main below, which of them will throw? Select all that apply. static void Main(string[] args){ Formula f1 = new Formula("1 / 1_a"); Formula f2 = new Formula("1 / _1"); Formula f3 = new Formula("1 / _1", Normalizer1, Validator1); Formula f4 = new Formula("1 / A1", Normalizer1, Validator1); Formula f5 = new Formula("5 + 5", s => s, s => false); } static bool Validator1(string s){ return Char.IsLower(s[0]); } static string Normalizer1(string s){ return s.ToLower(); } - Instantiating f1 will throw - Instantiating f2 will throw - Instantiating f3 will throw - Instantiating f4 will throw - Instantiating f5 will throw
- Instantiating f1 will throw - Instantiating f3 will throw
Consider the following snippet of C# code: public static class MathUtils { // Calculate the factorial of any integer public static int Factorial(int n) { if (n < 0) throw new ArgumentOutOfRangeException(); if (n == 0) return 1; else if (n == 1) return 1; else return Factorial(n - 1); } } Which of the following are design or style problems with this code? Select all that apply. - It repeats itself, and should be simplified with a helper method - It unnecessarily handles an error case (n<0) which is already handled by the rest of the code - It handles too many special cases, and could be shortened to consider fewer of them - It does not have narrow enough scope, it would be better to make the class non-static
- It handles too many special cases, and could be shortened to consider fewer of them
Consider the following C# code snippet, and assume it compiles: foreach(Thing t in things){ } Which of the following must be true about the variable things? Select all that apply. -It has been assigned a value -It refers to an array of Thing -It refers to a List<Thing> -Its type implements IEnumerable
- It has been assigned a value - Its type implements IEnumerable
What will happen when the following C# code is built and then run? public class Thing { public string? X {get; set;} public Thing(string x) {X = x;} public static void Main(string[] args) { Thing thing = new Thing("a"); Console.WriteLine(thing); } } - It will build successfully, but crash with a StackOverflow exception when run because the setter causes infinite recursion - There will be a build time warning because something of type string is saved in a variable of type string? - There will be a build time error because something of type string is saved in a variable of type string? - There will be either a build time error or warning depending on whether you've checked "Treat Errors as Warnings" - It will build and run with no warnings, errors, or exceptions.
- It will build and run with no warnings, errors, or exceptions.
Consider this unit test for a PS2 DependencyGraph: [TestClass()] public class DependencyGraphTest{ private DependencyGraph dg = new DependencyGraph(); [TestMethod()] public void EmptyRemoveDoesNotFail(){ dg.AddDependency("x", "y"); Assert.AreEqual(1, dg.Size); dg.RemoveDependency("x", "y"); Assert.AreEqual(0, dg.Size); } } Assume there are other tests in the test class that are not show here. Which of the following are design problems exhibited by this test? Select all that apply. Note that not all options are necessarily design problems. - It uses more than one DependencyGraph method - There is no comment for the test - Its state is not self-contained - It is not testing any useful corner cases
- Its state is not self-contained
Which of the following are true about JIT compilation? Select all that apply. - The time it takes between starting a program (e.g. double clicking it) and executing the first machine instruction specific to the program should be lower (faster) with a JIT compiled program - JIT compilation can help make a program portable to multiple systems - Executing a JIT compiled program requires additional software to be installed on the system - JIT compilation requires static linking
- JIT compilation can help make a program portable to multiple systems - Executing a JIT compiled program requires additional software to be installed on the system
In PS3, under what conditions should Formula's Evaluate method throw an exception? Select all that apply. - When divide by 0 occurs - When looking up a variable determines it has no value - When the formula contains an unknown token - When the validator delegate rejects a variable token - None of the above
- None of the above
If you you overload the == operator for some class, what else should you do to follow good software engineering principles? Select all that apply. - Overload the != operator for that class - Override the Equals method for that class - Make the class immutable
- Overload the != operator for that class - Override the Equals method for that class
A C# program developed in Windows can be run on a machine with a different operating system such as Linux, as long as (select all that apply) - The other machine has a .NET runtime installed - The other machine has Visual Studio installed - All of the libraries used by the program are available on the other machine - It can not be run on another operating system
- The other machine has a .NET runtime installed - All of the libraries used by the program are available on the other machine.
Which of the following are software engineering advantages of an immutable class? Select all that apply. - We can pass a reference to an immutable object to any method and be guaranteed that the method does not modify the object - If properly implemented, GetHashCode will always return the same value when invoked on an immutable object - Reference variables of an immutable type cannot be reassigned - If the constructor of an immutable class does error-checking, such as to ensure all fields have valid values, then the object is guaranteed to always have valid fields
- We can pass a reference to an immutable object to any method and be guaranteed that the method does not modify the object - If properly implemented, GetHashCode will always return the same value when invoked on an immutable object - If the constructor of an immutable class does error-checking, such as to ensure all fields have valid values, then the object is guaranteed to always have valid fields
Which of the following will result in nullness warnings/errors? Select all that apply - bool? b = null; - string s; s = "abc"; - string s = "abc"; s = null; - public string foo(int x) { if(x > 0) return "pos"; else if (x < 0) return "neg"; else return null; }
- string s = "abc"; s = null; - public string foo(int x) { if(x > 0) return "pos"; else if (x < 0) return "neg"; else return null; }
Which of the following types should appear somewhere in your Spreadsheet class in PS4? Select all that apply. Hint: reading the signatures of the PS4 skeleton code will help you partly answer this question. - string/String - double/Double - Formula - FormulaError
- string/String - double/Double - Formula
Consider this code using a Spreadsheet from PS5. Spreadsheet s = new Spreadsheet(); s.SetContentsOfCell("b1", "=5 + a1"); object x = s.GetCellValue("b1"); What is the result of running this code? - x is a double with a value of 5 - x is a string with a value of "=5+a1" - x is a FormulaError - An exception is thrown
- x is a FormulaError
Consider the following specification for an method that returns JSON: /// <summary> /// Returns a JSON object representing a class which has the following fields: /// "num" - the number of the class /// "name" - the name of the class /// "prof" - a JSON object representing the professor consisting of the following fields: /// "uID" - the professor's uID /// "students" - an array consisting of student objects. Each student has the following fields: /// "uID" - the student's uID /// "grade" - the student's grade in the class /// </summary> Which of the following JSON pieces adhere to the above specification? Select all that apply. - {"num": 5530, "name": "Databases", "prof": "uID": 1, "students": [{"uID": 2, "grade": "A"}, {"uID": 3, "grade": "B"}]} - {num: 5530, name: "Databases", prof: {uID: 1}, students: [{uID: 2, grade: "A"}, {uID: 3, grade: "B"}]} - {"num": 5530, "name": "Databases", "prof": {"uID": 1}, "students": [{"uID": 2, "grade": "A"}, {"uID": 3, "grade": "B"}]} - {"num": 5530, "name": "Databases", "prof": {"uID": 1}, "students": {["uID": 2, "grade": "A"], ["uID": 3, "grade": "B"]}} - {"num": 5530, "name": "Databases", "prof": {"uID": 1}, ["students": {"uID": 2, "grade": "A
- {"num": 5530, "name": "Databases", "prof": {"uID": 1}, "students": [{"uID": 2, "grade": "A"}, {"uID": 3, "grade": "B"}]}
Consider the C# code below: 1 static IEnumerable<int> Primes() { 2 yield return 2; 3 int p = 3; 4 while(true) { 5 if (IsPrime(p)) 6 yield return p; 7 p += 2; 8 } 9 } 10 11 static void Main(string[] args){ 12 IEnumerable<int> primes = Primes(); 13 foreach(int p in primes) 14 Console.WriteLine(p); 15 } Assume that breakpoints are placed on lines 2 and 6. If the program is started in Debug mode, and continue is pressed twice, how many numbers have been printed after the debugger pauses again? Assume IsPrime is a helper that determines if a number is prime, and does not print anything.
2 (with margin: 0)
Consider the previous question. What is the maximum number of frames on the stack during execution of this program? Assume Console.WriteLine does not call any other methods. Hint: remember that frames are pushed when a method is invoked, and popped when it returns.
3 (with margin: 0)
Which lines in the below method are dead code? Select all that apply. 1 public static void Foo(bool b) 2 { 3 if(b){ 4 return; 5 Console.WriteLine("a"); 6 } 7 else 8 Console.WriteLine("b"); 9 if(false) 10. Console.WriteLine("c"); 11 throw new Exception(); 12 return; 13 } 4 5 6 8 10 11 12 13
5 10 12
Consider the below C# snippet, and assume some non-static class Thing has has a public int x and is available to the scope of the snippet: Thing t1 = new Thing(); t1.x = 5; Thing t2 = t1; t2.x++; t2 = new Thing(); t2.x = 10; After executing the snippet, what is the value of t1.x?
6
In class today we discussed that variables can hold functions, and I said that we would discuss how to define the type of this variable using delegates on Tuesday. Just knowing that m and intM are two variables that can hold functions is enough information to answer this question, e.g. you don't need to understand line 1. Consider the below C# snippet with line numbers. 1 delegate void SomeIntMethod(int x); 2 class Program 3 { 4 public static void PrintInt(int i){ 5 Console.WriteLine(i); 6. } 7. public static void Foo(SomeIntMethod m){ 8. m(15); 9 } 10 static void Main(string[] args){ 11 SomeIntMethod intM = PrintInt; 12 Foo(intM); 13 } 14 } On which line is PrintInt invoked? Enter 0 if it is never invoked.
8
Consider the below C# classes: public abstract class Shape{ private string color; public Shape(string c){color = c; } } public class Square : Shape{ private int size; public Square(int s)/*missing code*/ { size = s; } } Fill in the blank to replace /*missing code*/ above so that the Square class compiles and all squares are created with a color of "blue". You answer should not contain any spaces.
:base("blue")
Marking members of a class as private so that the outside users of the class can't see the implementation details is important for data protection, but is also an example of:
Abstraction
Consider the following C# snippet: static void Main(string[] args){ string s = "hi"; int i = 15; MysteryDelegate foo = (a, b) => a.Length > b; if (foo(s, i)) return; } Fill in the missing parts of the delegate declaration below so that it compiles with the given code above. Give exact C# code with no spaces. Do not use var. delegate ______ MysteryDelegate( ______ x, ______ y);
Answer 1: Boolean Answer 2: String Answer 3: Int32 or int
Suppose you are working on code with a team and you have made some commits in your local repository, but someone else has made changes on the server in the same branch since the last time you synchronized. If you try to push your commits, it will result in a ____________ . To synchronize your changes, you must first ____________ , then ____________ , then ____________ then ____________ . Note: some git tools will automatically create a commit for every merge (even though they are two operations). Assume the tool does not do this, and that merges must be explicitly committed.
Answer 1: conflict Answer 2: pull Answer 3: merge Answer 4: commit Answer 5: push
In the C# code below, what are the types of the lambda parameters 'x' and 'y'? Give the exact C# types, respecting case sensitivity, and with no spaces. Func<float, int, double> f = (x, y) => x * y; C# type of x: C# type of y:
Answer 1: float Answer 2: int
In the C# code below, what are the types of the lambda parameters 'x' and 'y'? Give the exact C# types, respecting case sensitivity, and with no spaces. delegate bool ComplexOp(int a, float b); private static void ApplyOp(float[] arr, ComplexOp op){ foreach(float f in arr) op(2, f); } static void Main(string[] args){ float[] floats = { 3.14f, 1.1414f }; ApplyOp(floats, (x, y) => x > y); } C# type of x: C# type of y:
Answer 1: int Answer 2: float
Consider an alternate implementation of the StringUtil class that provides a general-purpose filtering method (FilterString), instead of just one to filter out the digit characters. The specific filter to be applied (such as return only the digit characters) is provided by the user. Fill in the blanks in the code below so that the StringUtil class is implemented correctly. public class StringUtil{ public delegate ___________ CharFilter(char c); public List<char> FilterString(string s, f) { List<char> returnVal = new List<char>(); foreach (char c in s) if ( ___________) returnVal.Add(c); return returnVal;}} Now fill in the blank below so that FilterString is used to return a list of only the uppercase letters ,via Char.IsUpper. StringUtil sUtil = new StringUtil(); List<char> L = sUtil.FilterString("How aRe you?", ___________); Give exact C# code, and do not use any whitespace in your answers. Do not use Func notation (if you don't know what that is, you don't need to).
Boolean CharFilter f(c) Char.IsUpper
In the Demo application we made, what variable in the MainPage contains its top level GUI element? That is, in the following snippet, what should go in the blank to return a ScrollView? Type only the (case-sensitive) name of the variable, without punctuation. ScrollView sv = (ScrollView)this.______;
Content
Starting with your local and remote repositories synchronized, if you then make changes to a file in your local repository that you want submitted as part of PS1, you must first ___________ , then ___________ .
commit push
Consider the question before the previous question. If Thing was a struct instead of a class, the space allocated for Main's stack frame would: - get larger - get smaller - not change in size
get larger
In computing, the programming language is a ________ ["higher", "lower"] level of abstraction than the operating system, and within a programming language, individual statements are a ________ ["higher", "lower"] level of abstraction than functions.
higher lower
Consider a class (below) that provides a GetDigits method for returning a list of all of the digit characters in a string. For example, if the input is "a1bc2", the output should be a list containing '1' and '2'. public class StringUtil { private static List<char> digits = new List<char>(); public List<char> GetDigits(string s) { foreach (char c in s) if (Char.IsDigit(c))digits.Add(c); return digits; } } The class is buggy, and GetDigits only seems to work correctly sometimes. Here is an example of using StringUtil: StringUtil sUtil = new StringUtil(); List<char> digits = sUtil.GetDigits("abc123"); // returns the correct resultStringUtil sUtil2 = new StringUtil(); digits = sUtil2.GetDigits("xyz456"); // returns an incorrect result Change the StringUtil class by removing exactly one keyword from the code, so that the second call to GetDigits in the example above returns the correct result. Give the keyword exactly as it appears in the code with no extra spaces. Hint: Char.IsDigitLinks to an external site. is a built-in method in C#, and it works correctly. Keyword to remove:
static
Consider this C# class: public class Thing { Stack<int> s; bool someBool; public Thing(bool b) { someBool = b; s = new Stack<int>(); } public void Foo(int x) { Console.WriteLine(x); } } and this Main method: static void Main(string[] args){ Thing t = new Thing(true); int i = 5; t.Foo(i); } Assume all necessary using declarations exist. When the program is running, where do each of the below pieces of data reside? (stack/heap) Hint: remember the difference between a reference variable and an object. t: the Thing object: s: the Stack object: someBool: i: x:
t: stack the Thing object: heap s: heap the Stack object: heap someBool: heap i: stack x: stack
What is the name of the attribute that creates a member variable for an XML element? That is, in the following snippet what should go in the blank to create a member variable named Foo in the corresponding code-backing file? <Button _____="Foo" />
x:Name