C# Flashcards

(224 cards)

1
Q

What is a variable?

A

~ storage location in memory (RAM) that a programmer can use to store data

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

What parts does a variable have? (5)

A
  1. identifiers: labels to refer to storage location
  2. scope: availability of data while program executes / in scope if still in memory
  3. address: actual location in RAM
  4. data type: defines storage and proper use of data
  5. value: actual data that is stored in variable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

List the 5 different .NET data types.

A

integer

floating-point

boolean

char

built-in reference

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

What are the 2 subtypes of .NET built-in reference data types?

A

string and object

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

List the 8 different .NET integer data types with their respective Visual C# name.

A
  • System.Byte - byte
  • System.Int16 - short
  • System.Int32 - int
  • System.Int64 - long
  • System.SByte - sbyte
  • System.UInt16 - ushort
  • System.UInt32 - uint
  • System.UInt64 - ulong
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

C# byte data type

A

8 bit, unsigned, 0 to 255

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

Give description (sign and storage) and range of the C# short data type.

A

signed, 16 bit, -32768 to 32767

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

Give description (sign and storage) and range of the C# int data type.

A

32 bit, signed, -2^31 to 2^31-1

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

Give description (sign and storage) and range of the C# long data type.

A

64 bit, signed, -2^63 to 2^63-1

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

Give description (sign and storage) and range of the C# sbyte data type.

A

8 bit, signed, -128 to 127

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

Give description (sign and storage) and range of the C# ushort data type.

A

16 bit, unsigned, 0 to 65535

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

Give description (sign and storage) and range of the C# uint data type.

A

unsigned, 32 bit, 0 to 2^32-1

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

Give description (sign and storage) and range of the C# ulong data type.

A

64 bit, unsigned, 0 to2^64-1

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

List the 3 floating point data types with their type name and their C# name.

A
  1. System.Single - float
  2. System.Double - double
  3. System.Decimal - decimal
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Give description, precision and range of the float floating point data type.

A
  • 32 bit - 7 significant digits - +/-1.4 x 10^-45 to +/-3.4 x 10^38
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Give description, precision and range of the double floating point data type.

A
  • 64 bit - 15 - 16 sign. digits - +/-5.0 x 10^-324 to +/-1.7 x 10^308
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Give description, precision and range of the decimal floating point data type.

A
  • 128 bit - 28 sign. digits - +/-1.0 x 10^-28 to +/-7.9 x 10^28
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the System.Boolean type called in C#?

A

bool

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

What values can Boolean take on?

A

only true and false

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

What is the System.Char called in C# and what does it represent?

A

Char and it represents a single 16-bit Unicode character by enclosing it in single quotes.

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

What is the use of a string data type?

A

You can assign a series of char data, e.g. a word or a paragraph, to a string variable.

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

What difference is there between the assignment of a char literal in contrast to a string literal.

A
  • Char values are enclosed in single quotes.
  • String values are enclosed in double quotes.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What type of data can you assign to System.object?

A

It is the super type. All others derive from it and you can assign any object or value to it.

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

How do you assign an object to the object type?

A

object myObject;

myObject = 543

myObject = new System.Windows.Forms.Form()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
When do implicit conversions happen in C#?
- automatically performed whenever conversion can be performed without loss of data
26
Code an implicit conversion of a variable storing the number 100 into 64 bit.
int SomeNumber = 100; long LongVariable; LongVariable = SomeNumber;
27
What is an explicit conversion also called?
a cast
28
Give a generic example of an explicit conversion of a chosen number.
int someInteger = 22 short someShort; someShort = (short)someInteger;
29
What is Parse? (4)
* used to create a numeric value from a string * can convert user data entries from text boxes into usable data * results in an error if string cannot be read as a numeric value * Parse is a **static (Shared)** and must be called from the **type object** rather than an **instance**
30
Give a simple example for a Parse conversion of a string '123456'.
int I; string S; S = "123456"; I = int.Parse(S);
31
Give a list of the arithmetic operators under C#.
* addition, subtraction, multiplication * division with integers * division with floating points * modulus * unary (=, increment/decrement operators, shortcut operators (+=, -=, \*=, /=, %=), cast operator)
32
Which comparison operators does C# know?
/\* relational: \< \> \<= \>= equality: == != \*/
33
What logical operators does C# know? (5)
* logical AND ("&") * logical OR (|) * logical XOR (^) * conditional AND ("&&") * conditional OR (||)
34
Give the rough order of precedence of operators in C# from highest to lowest? (14)
* primary * unary * multiplicative * additive * shift * relational * equality * logical AND * logical XOR * logical OR * conditional AND * conditional OR * ternary * assignment
35
Microsoft Visual Studio is the main ... (IDE) from Microsoft.
Integrated Development Environment
36
What is an Integrated Development Environment? (4)
* is a software suite that consolidates the basic tools developers need to write and test software * contains a code editor, a compiler or interpreter and a debugger * accessed through a single graphical user interface (GUI) * may be a standalone application or it may be included as part of one or more existing and compatible applications
37
In which editions is Microsoft Visual Studio available? (4)
* Visual Studio Express Editions * Visual Studio Standard Edition * Visual Studio Professional Edition * Visual Studio Team System
38
Can you mix and match Frameworks and Visual Studio Editions?
No.
39
List the .NET Framework editions and the complementing Visual Studio edition.
* .NET Framework 1.0 - Visual Studio 2002 * .NET Framework 1.1 - Visual Studio 2003 * .NET Framework 2.0 - Visual Studio 2005 * .NET Framework 3.5 - Visual Studio 2008 * .NET Framework 4 - Visual Studio 2020
40
What can you build in Visual Studio 2010? (6)
* rich Windows applications and libraries * Windows services * Console application * Dynamic web applications and libraries * XML web services (cross platform, cross language, cross firewall) * smart device applications
41
Windows apps require ... Windows apps provide a consistent ... (...) for communicating with drivers, devices, and so on.
a Windows Runtime Environment, API (Application Programming Interface)
42
.NET apps require ... .NET apps provide a ... for working with Windows, data structures, types, and so on. ... must be installed to run any .NET apps.
.NET Runtime Environment, consistent API, .NET runtime
43
What are the 2 components of .NET Framework?
Framework Class Library (FCL) [here Base Class Library] and Common Language Runtime (CLR)
44
What is CLR? (4)
* ~an **application virtual machine** that provides services such as security, memory management, and exception handling. (As such, computer code written using .NET Framework is called **"managed code"**.) * it's a **software** **environment**, programs written for .NET Framework execute in (in contrast to a hardware environment) * process known as **just-in-time compilation** converts compiled code into machine instructions which the computer's CPU then executes
45
What is the FCL? (3)
* a large class library named **Framework Class Library** * provides **language interoperability** (each language can use code written in other languages) across several programming languages * consists of an **object-orientated collection of reusable classes (types)** that we can use to develop applications
46
List the 5 layers of .NET Framework architecture.
1. VB, C++, C#, JScript, ... 2. Web Forms (ASP.NET), Windows Forms 3. Base Class Library 4. Common Language Runtime 5. Windows
47
What is "managed code"?
* ~ a **computer program source code** that executes only under management of a **CLR virtual machine** like .NET Framework or Mono * written in **1 of over 20 high-level programming languages** that are available for use with the Microsoft .NET Framework, including C#, J#, Microsoft Visual Basic .NET, Microsoft JScript and .NET
48
The CLR consists of ... that load the ... (IL code) of a program into the runtime, which compiles the IL code into ...
class loader, intermediate language code, native code
49
What is IL code?
~ low level language designed to be read and understood by the CLR
50
What is a runtime?
~ the period of the program lifecycle phase during which a computer program is executing
51
What is "unmanaged code"?
~ refers to programs written in C, C++, and other languages that do not need a runtime to execute
52
Who developed C#?
Anders Hejlsberg and his team during the development of .Net Framework.
53
Give the most common advantages for using C#. (8)
- modern, general-purpose programming language - object oriented - component oriented - easy to learn - structured language - produces efficient programs - can be compiled on a variety of computer platforms - part of .Net Framework
54
List important features of C#. (11)
Boolean Conditions Automatic Garbage Collection Standard Library Assembly Versioning Properties and Events Delegates and Events Management Easy-to-use Generics Indexers Conditional Compilation Simple Multithreading LINQ and Lambda Expressions Integration with Windows
55
What is Mono?
* an open-source version of the .NET Framework which includes a C# compiler and runs on several operating systems * runs on Android, BSD, iOS, Linux, OS X, Windows, Solaris, and UNIX
56
What is a namespace?
~a collection of classes
57
What does Console.ReadKey(); do?
- makes the program wait for a key press - prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET.
58
What is the entry point for all C# programs?
the Main method
59
What is computer decision making generally like?
* all computer decisions are yes-or-no decisions (boolean values: true and false) * Decision structure is a logical structure that involves choosing between alternative courses of action based on some value within program
60
What do you use an if-statement for?
- use to make a single-alternative decision - use it to determine whether an action will occur
61
What is the general structure of an if-statement?
if (testedExpression) statement; - **testedExpression** is any expression that evaluates as true or false - **statement** represents the action that will take place if the expression evaluates as true
62
What kind of expressions can you test for in C# if-statements?
Must be boolean! - comparison statements such as e.g. \>= or == - boolean variables such as e.g. IsValidNumber
63
What is the format to execute more than one statement in an if-statement?
**Use curly brackets!** ## Footnote if (hoursWorked \> FULL\_WEEK) **{** regularPay = FULL\_WEEK \* rate; overtime = (hoursWorked – FULL\_WEEK) \* OT\_RATE \* rate; **}**
64
What happens if you declare a variable within a statement block?
It can be used only within that block! Declare it outside the if-statement to be able to continue using it.
65
What is the format to code dual-alternative if decisions?
if (testedExpression) statement; else statement; *Else* without *if* is illegal!
66
What are nested if statements?
~statements in which if structure is contained inside of another if structure
67
When do you use nested if statements?
-when two conditions must be met before some action is taken
68
Explain the decision making process in the following code: if (saleAmount \> 1000) if (saleAmount \< 2000) bonus = 50; else bonus = 100;
1. If saleAmount is between $1000 and $2000, bonus is $50 because both evaluated expressions are true 2. If saleAmount is $2000 or more, bonus is $100 because the first evaluated expression is true and the second one is false 3. If saleAmount is $1000 or less, bonus is unassigned because the first evaluated expression is false and there is no corresponding else
69
What are common mistakes in writing up if statements?
- placing a ; right after the testedExpression - using the assignment operator = instead of the equality operator == in a testedExpression - not using curly brackets to group several action statements
70
What happens if you code several executable actions for an if statement, but forget to put them into curly brackets?
- they are not grouped, so only the first statement depends on the testedExpression - after the if statement, instead of breaking out of the expression, the other action statements will be carried out regardless as independent expressions
71
What happens if you use the assignment operator in a testedExpression instead of the equality operator? if (number = 3) statement;
Illegal! -will produce error
72
What happens if you place a semicolon right after the testedExpression in an if statement? if (testedExpression) ; statement;
- testedExpression has no action - statement will execute independently of the testedExpression
73
74
What types of loops exist?
while for do..while
75
One execution of any loop is called an ...
iteration
76
What are the characteristics of a while loop?
~executes body of statements continuously a long as the Boolean expression at the entry of the loop is true
77
What is the syntax of a while loop?
while (Boolean expression) loop body;
78
What is a loop called that executes a specific number of times?
A definite loop or a counter controlled loop.
79
What is the general syntax of a counter controlled loop? ## Footnote Loop control variable = a Limiting value = B
int a; const int B = 11; a = 1; while (a \< B) { Console.WriteLine(a) a = a + 1; }
80
What are the syntax rules for a definite loop?
1. intialise control variable (determines whether execution continues) (a) 2. while control variable doesn't pass limiting value (B), loop continues to execute loop body 3. loop body must include statement that alters loop control variable
81
When can you suspect you are dealing with an infinite loop?
* the same output is displayed repeatedly * the screen remains idle for extended periods of time
82
How do you exit an infinite loop?
with Ctrl-C or Break
83
What coding errors can cause an infinite loop? (4)
* empty body caused by misplaced semicolons [while (a \< B)**;**] * Boolean statement always evaluating to true [while (2 \< 4)] * not increasing control variable in loop body * forgetting curly brackets for grouped statements in loop body while (a \< B) Console.WriteLine(a); a++;
84
Infinite loops are commonly used in ...
... data input validation / testing.
85
When is a for loop commonly used?
Is used when a definite number of iterations is required.
86
Give the general syntax of a for loop.
for (initialise; evaluate; alter) loop body; **_e.g.:_** for (int a = 1; a \< 5; ++a) Console.WriteLine(a);
87
Give common properties of a for loop. (4)
* variable can be declared outside the for loop * a variable declared within a for loop is local, it goes out of scope outside of the loop * you can leave a portion of the for loop empty: for(; j \< 7; ++j) * the same variable needs to turn up in all parts of the statement
88
What other tasks can you perform with a for loop? (5)
* can initialise more than one variable: for (i = 1, g = 4; i \< 10; ++i) * can perform more than one test: for (a = 0; a \< 9 && u \> 1; ++a) * decrement instead: for (x = 0; x \<= 9; --x) * alter more than one variable: for (i = 1; i \< 5; ++i, sum += k) * can pause program by leaving out loop body: for (k = 1; k \<= 10; ++k);
89
Why would you use a do-while loop?
A do-while loop the control variable at the bottow of the loop when one iteration has already occured. There will always be at least one iteration.
90
What is the syntax of a do-while loop?
do { loop body; } while (Boolean expression);
91
What is another name for the do-while loop?
posttest loop
92
Write a simple program: You have a given bank balance, year and interest rate. Calculate the balance after the interest has been applied. Display the results and ask the user if they want to see the result for the next year upon entering "y" or "n". Then, iterate.
* do { *//do loop* * balance = balance + balance \* INT\_RATE; *//interest rate is constant* * tempBalance = (int) \* (balance \* 100); *//convert to int, but will lose accuracy, to preserve 2 decimals multiply by 100* * balance = tempBalance / 100.0; *//divide by 100 to get 2 decimals back and convert to double by using 100.0* * Console.WriteLine("After year {0} at {1} " + "interest rate, balance " + "is $ {2} ", year, INT\_RATE, balance); * year = year + 1; *//increase counter* * Console.WriteLine("Want to see the balance " + "at the end of another year? " + " y or n? "); * response = Convert.ToChar(Console.ReadLine()); *//user input* * } while (responseChar == 'y'); *//tested loop condition*
93
What are nested loops?
~ When you place another loop within a loop.
94
A loop that completely contains another is an ...
... outer loop.
95
A loop that falls entirely within the body of another is an ...
... inner loop.
96
What are the properties of nested loops? (3)
* can nest any type of loop within any other * can never overlap * no limit to how many loops can be nested
97
Code: Print 3 mailing labels for each of 20 customers.
for (customer = 1; customer \<=20; ++customer) for (label = 1; label \<= 3; ++label) { print statements; }
98
How can you improve loop performance? (4)
1. make sure the loop doesn't contain unnecessary statements or operations 2. consider the order of operations for short-circuit operators 3. make a comparison to 0 4. employ loop fusion
99
How do you make sure the loop doesn't contain unnecessary statements or operations?
* should not arise in the tested expression or the loops body _e.g.:_ while (x \< a + b) --\> sum = a + b; while (x \< sum);
100
How do you consider the order of evaluation for short-circuit operators?
* each part of an AND or OR statements is only tested until found true or false * you can cut down on iteration-time if you place tested statements in the order they are more likely to be true _e.g.:_ while (A || B) --\> swap if B more likely --\> while (B || A)
101
How do you make a comparison to 0 to improve loop performance?
* improves performance if you compare to 0 rather than to another value _e.g.:_ a test from upwards from 0 to 1000 is slower than downwards from 1000 to 0
102
How can you use loop fusion?
* if 2 loops have the same tested expression and the methods do not depend on each you, you can fuse them _e.g.:_ for (int i = 0; i \< 40; ++i) method1(); for (int i = 0; i \< 40; ++i) method2(); AS for (int i = 0; i \< 40; ++i) { method1(); method2(); }
103
What is an array?
A way to store multiple variables of the same type.
104
Why do we use arrays? (4)
* to manipulate sets of items * to perform some operation on each item in a set * to avoid repeating code * can be used in loop constructs to perform the same actions on each object
105
How do you declare and instantiate an array?
* variable type*[] *variable name* * variable name* = new *variable type*[*size*]; _e.g.:_ int[] x x = new int[4];
106
Declare and instantiate an array in one line.
int[] numbers = new int[4];
107
If the following numbers make up an array "array1", how to you access the third number? 88, 6, 12, 100, 76
*array\_name*[*index*] = *value* array1[2] = 12;
108
Initiate and declare an array called "numbers" including its' values, 44, 2, 39, 11.
int[] numbers = new int[4] {44, 2, 39, 11};
109
What properties does an array have pertaining to its structure? (5)
* array length once declared cannot be changed anymore * each value is assigned an int value in order of creation (index) * index values start from 0 * the last index value is always 1 smaller than the size of the array * if a non-existent index is referenced, you get an error
110
# Fill in the following blanks according in order of the red numbers given.
* 1: 5 * 2. to 6.: 0, 1, 2, 3, 4 * 7: index value * 8. to 12.: 0, 0, 0, 0, 0 default value * 13: 32 * 14: element
111
Use a for loop to iterate through an array.
int[] numbers = {20, 54, 7, 87}; for(int i = 0; i \< numbers.Length; i++) { TestLabel.Text += numbers[i] + ","; }
112
Describe procedural programming languages. (4)
* task is a series of step-by-step instructions * instructions executed in logical sequence * difficult to maintain * e.g. Assembler, Fortran, Cobol, C
113
What are the characteristics of object oriented programming languages? (4)
* the task is an object * objects contain data and instructions for tasks * a program is a collection of interacting objects * e.g. C#, C++, Java
114
Programmers refer to information about the problem they are solving as ...
... the problem domain.
115
What is OOP?
= Object-Oriented Programming * is a technique for managing problem complexity by defining objects from the problem domain
116
What is an object? (5)
* a programmatic concept that represents something * objects in the real world are e.g. cars, houses * each item exposes a specific functionality and has specific properties * an object is an instance of an individual class * contain data and instructions
117
What is a class?
* = a blueprint for an object * defines the common characteristics, e.g. every car has wheels, brakes
118
What is the composition of an object? (3)
* composed of **members**, that is... * ***fields*** that describe the state of an object * ***methods***, the set of instructions performed by an object
119
Give the simplified structure of a class and it's elements.
public class *ClassName* { //fields //properties //constructors //methods }
120
What is encapsulation? (5)
* objects should only interact with other objects through their public methods and properties * objects should contain all of the data they require and should contain all of the functionality that works with that data * internal data of an object should never be made available to other objects * this is implemented with access modifiers such as public, private, and protected * properties have a get method (public) used to access private data and a set method (public) to change private data
121
Declare 3 fields for student ID, student first name, and student last name.
private int studentId; private string firstName; private string lastName;
122
Declare the properties for an attribute eye colour.
public string EyeColour { get {return eyeColour;} set {eyeColour = value;} }
123
What is a constructor? (6)
* contains the instructions for creating an object * puts this object in a valid state * has same name as class & no return type * compiler will implicitly provide one if not declared (null constructor) * can provide with arguments * can provide several overloaded versions of constructor
124
Give another name for creating objects.
instantiation
125
What is a null constructor? Give it's syntax.
* if no other constructor has been explicitly declared the compiler inserts one: **public *Name*()** **{** **}**
126
Create an object for a new student, s1.
Student s1 = new Student();
127
Declare a constructor MyCar with the properties plate number, model, year, colour, and built type (sedan, hatch).
``` public MyCar(string plateNumber, string model, int year, string colour, BuiltEnum built) { this.plateNumber = plateNumber; this.model = model; this.year = year; this.colour = colour; this.built = built; } ```
128
What are methods? (4)
* define the behaviours of an object * is a step-by-step procedure for completing a task * objects interact with methods * methods are used to send and receive messages
129
What do methods roughly consist of? (3)
* meaningful name to describe the task * required information to complete a task * result of task completion
130
What are method arguments?
* the information required to complete the task * can require zero, one, or several arguments
131
What are method return values? (3)
* are the results of the method * methods can return zero or one value * keyword void is used to signify that the method does not return any information
132
Code a method to print the following information: * employee ID * first name * last name * age * job title (teacher, assistant, caretaker)
public string PrintInfo() { return empId + ", " + firstName + ", " + lastName + ", " + age + ", " + job; }
133
What is an instance / object variable? (3)
= a field * identify the data stored in each object of the class. * values of instance variables differentiate objects from others by defining its state
134
How do you reference instance variables?
* within the class definition, use the variable name * to reference the variable of an object by another object, use the object reference with dot notation
135
What are class / static variables? (5)
* associated with a class and are shared by all objects of the class * a given class will only have one copy of each of its class variables * class variables exist even if no objects of the class have been created * if value of class variable is changed, then the new value is available to all objects * use the keyword static
136
What are local / method variables?
* are the data used in a method * this data is temporary and does not exist once the method has completed execution
137
How is data stored in the RAM? (3)
Stack Heap static
138
What is the Stack? (4)
* where data required or referenced by methods is created * increases or decreases depending on the methods being used at any given time * methods are shared among objects * where the sequence of methods currently being used store their data
139
What is the Heap? (3)
* all objects are stored on the Heap * compiler does not need to know how much memory is needed, or how long the objects need to stay on the heap * objects storage is allocated when you use the keyword new
140
What is static storage? (3)
* means “in a fixed location.” * data that is needed for the entire program is stored in this space * as long as the program is running, this data will be available to all objects and all methods
141
Describe instance methods? (3)
* can only be accessed through an object of a class * can access any data members of the class by using the identifier * can access other methods of the same class, including static methods
142
Describe static / class methods? (3)
* are used independently of any objects being created * can be referenced in a static method * can only access instance methods or instance data after an instance of the class is created
143
What is overloading?
= when two or more methods (including constructors) are defined in the same class and given the same name
144
What are the rules for overloading methods or constructors? (4)
* names must be the same * number of arguments must be different * if the number of arguments is the same, at least one argument (by position) must have a different data type * changing only the return type for a method with the same name and same number and data type of arguments (by position), is not a valid overloaded method
145
What are enumerations?
=user-defined sets of integral constants that correspond to a set of friendly names
146
How do you declare an enumeration? (4)
* is declared before class declaration, as follows **public enum *NameEnum* { VALUE1, VALUE2, VALUE3 }** * the field: **private *NameEnum* name;** * properties: **public *NameEnum* name { get {return name;}** **set {name = value;} }** in the constructor: **public MyClass(*NameEnum* name)** **{** **this.name = name;** **}**
147
What is inheritance? (4)
* increases flexibility of class design * deriving new class definitions from an existing class * reuse of predefined classes * defines "is a" relationships among classes and objects
148
What is a base class? (3)
* a class can directly inherit from only one class, the base class * new class has all of the same members as the base class, and additional members can be added as needed * implementation of base members can be changed in the new class by overriding the base class implementation
149
What class is the root of all classes?
the Object class
150
Define Monkey as the sub class of Animal.
public class Monkey **:** Animal { }
151
The base class is called Person and has the properties ID, first name, and last name. The sub class is called Customer and has a property, rate. Declare the constructors for the base and the sub class.
**_Base class:_** * public Person(int Id, string firstName, string lastName) * { * this.personId = personId; * this.firstName = firstName; * this.lastName = lastName; * } **_Sub class:_** ``` public Customer(int id, double rate):base(id) { this.rate = rate; } ```
152
What does "overriding base class members" refer to? (3)
* when inheriting from a base class, you can provide a **different implementation** for base class members by overriding them * allows you to alternate your own implementation for a base class member **of the same name** * only base class methods and properties can be overridden
153
How do you override base class members?
154
How do you override base class members? (5)
* new implementation must have identical signature, return type, and access level as base member * to override a base class it must be marked as virtual * virtual keyword cannot be used with static, abstract, private, and override * can declare a different implementation of a member by using override keyword * new implementation's access depends on type of object
155
How do you override the following scenario? Base class: Animal, Animal moves Subclass: Monkey, monkey jumps Monkey
public class Animal { public virtual string Move() { return "Animal moves"; } } public class Monkey : Animal { public override string Move() { return "Monkey jumps"; } }
156
How do you hide base class members? (4)
* replace the base class implementation with a new implementation * new implementation must have same signature as the member that is being hidden, but it can have a different access level, return type, and completely different implementation * use new keyword * new implementation's access depends on the type of the variable rather than the type of the object
157
How do you hide the following base class method? Base class: Animal, Animal moves Subclass: Monkey, monkey jumps Monkey
public class Animal { public string Move() { return "Animal moves"; } } public class Monkey : Animal { public new string Move() { return "Monkey jumps"; } }
158
List the existing access modifiers? (5)
public private internal protected protected internal
159
From where can you access a member with the access modifier "public"?
* can be accessed from anywhere
160
From where can you access a private member?
* can only be accessed by members within the class that defines it
161
From where can you access a member with the access modifier "internal"?
* can be accessed from all classes within the assembly (library .dll), but not from outside the assembly
162
From where can you access a protected member?
* can only be accessed by members from within the class that defines it or classes that inherit from it
163
From where can you access a member with the access modifier "protected internal"?
* can be accessed from all classes within the assembly or from classes inheriting from the owning class
164
What types of collections exist and what is their respective namespace?
**_Non-genericcollections_** System.Collections namespace **_Genericcollections_** System.Collections.Generic namespace
165
List the types of non-generic collections. (7)
* ArrayList * Stack * Queue * Hashtable * SortedList * Dictionary * SortedDictionary
166
What is an ArrayList?
* a simple resizable,index based collection of objects * similar to a single-dimensional array that you can resize dynamically
167
What is a Stack (collection)?
* a LIFO collection of objects
168
What is a Queue?
* FIFO collection of objects
169
What is a Hashtable?
* a collection of name/value pairs of objects that allows retrieval by name or index
170
What is a SortedList?
* a sorted collection of name/value pairs of objects
171
What is a Dictionary?
* a set of keys and their associated values
172
What is SortedDictionary?
* to maintain the collection in order by the key
173
What is the namespace of non-generic spezialised collections?
System.Collections.Specialize
174
What types of non-generic spezialised collections exist? (4)
* BitArray * StringCollection * StringDictionary * NameValueCollection
175
What is a BitArray?
* a collection of boolean values
176
What is a StringCollection?
* a simple resizable collection of strings
177
What is a StringDictionary?
* a collection of name/values pairs of strings
178
What is a NameValueCollection?
* a collection of name/value pairs of strings that allows retrieval by name or index
179
What are generic collections?
* support the storage of both value types and reference types * only a single datatype is allowed to be stored in a generic collection
180
List the types of generic collections that exist. (5)
* Generic Dictionary * Generic List * Generic Queue * Generic Stack * Generic LinkedList
181
What is a Collection Interface?
* allows a collection to support a different behaviour
182
List types of collection interfaces. (8)
* IComparable * ICollection * IList * IComparer * IEqualityComparer * IDictionary * IEnumerable * IEnumerator
183
What does the collection interface IComparable do?
* defines a generalized comparison method that a value type or class implements to create a type-specific comparison method
184
What does the collection interface ICollection do?
* support a common way of getting the items in a collection, and away to copy the collection to a narray object * derives from IEnumerable
185
What does the collection interface IList do?
* provide a common way to add/remove items
186
What does the collection interface IComparer do?
* exposes a method that compares 2 objects
187
What is the function of IEqualityComparer?
* defines methods to support the comparison of objects for equality
188
What does the collection interface IDictionary do?
* represents a non-generic collection of key/value pairs
189
What is the function of IEnumerable?
* exposes the enumerator, which supports a simple iteration over a non-generic collection
190
What is IEnumerator there for?
* supports a simple iteration over a non-generic collection
191
How do you add a value to a collection?
**_Add method / at the end:_** * CollName*.Add(*value*); e. g. myCollection.Add("burgers"); e. g. myCollection.Add(new DateTime(2017, 12, 31)); **_Insert method / at specific position:_** * CollName*.Insert(*index*, *value*); e. g. myCollection.Insert(0, "programming");
192
How do you remove a value from a collection? (3)
**_Remove method / specific value:_** * CollName*.Remove(*value*); e. g. myCollection.Remove("burgers"); e. g. myStudents.Remove(new Student(2, "Bob")); **-\> requires overriding Equals method!!** **_RemoveAt method / from specific position:_** * CollName*.RemoveAt(*index*); e. g. myCollection.RemoveAt(2);
193
How do you empty a collection?
*myCollection*.Clear();
194
How do you determine the index of a particular item in a collection?
* CollName*.IndexOf(*value*); e. g. MessageBox.Show(myCollection.IndexOf("programming").ToString());
195
How do you check if a particular object is contained in a generic collection?
bool found = *CollName*.Contains(new *ObjName*(*value1*, *value2*)); MessageBox.Show("Has object been located?" + found); e.g.: bool found = myStudents.Contains(new Student(1, "Brian")); MessageBox.Show("Brian is found?" + found); **Note:** Requires overriding Equals method to compare**!!**
196
How do you override the Equals method for Contains() and Remove() for generic lists involving objects? (The object is called Student.)
public override bool Equals(object obj) { Student anotherStudent = (Student)obj; //local var if (this.sId == anotherStudent.sId && this.sName == anotherStudent.sName) { return true; //equal } return false; //not equal }
197
How do you sort through a collection?
*CollName*.Sort(); **Note:** Sort for generic collection objects requires implementation of CompareTo method from IComparable**!!**
198
How do you implement the CompareTo method from IComparable for using Sort() on a generic collection involving an object? (The object is called Student.)
public int CompareTo(object obj) { Student anotherStudent = (Student)obj; return this.sId.CompareTo(anotherStudent.sId); }
199
What are abstract classes? (8)
* serve as a guideline for other classes * cannot be instantiated but used as a base class from which other classes can be derived * declared using the abstract keyword * can provide fully implemented members * can specify abstract members that must be implemented (override) in inheriting classes * can have abstract methods, and concrete methods and data * any class that includes an abstract method must be declared as abstract * force any non-abstract subclasses to provide an implementation for the abstract methods
200
What are sealed classes? (4)
* cannot be used as a base class * cannot be an abstract class * are used to prevent inheritance * when we override a method in a sub class, we can declare the overridden method as sealed using two keywords (sealed override) to prevent further overriding of this method
201
What is an interface?
* are abstract classes that define abstract methods
202
What is the purpose of an interface?
* to provide a mechanism for a subclass to define behaviors from sources other than the base class
203
What characteristics do interfaces have? (4)
* a class can inherit one class only and can implement many interfaces * can inherit other interfaces * all the methods in an interface are automatically public and abstract * a class that implements an interface is an instance of the interface class
204
What is polymorphism? (3)
* means "many forms” * allows the same code to have different effects at runtime depending on the context * you can create a subclass object using base class or any implemented interfaces as a reference type
205
Error handling is ...
... the way of coding to handle error conditions that may arise during the runtime of the program.
206
Exceptions are ...
... any unexpected or exceptional situations that occur when a program is running.
207
Errors may occur during ... and runtime. Errors should be prevented before ... However not all errors can be prevented due to ..., resource availability such as trying to open a file that does not exist, and other ...
compilation runtime unexpected user input vulnerabilities
208
What types of errors exist? (3)
* *Compile time errors** - occur when the program will not compile due to syntax error such as spilling, missing brackets, case-sensitive errors etc. * *Run time errors** - occur while the program is running * *Logical errors** - errors that the programmer makes when writing the code for the program that produce unexpected results
209
What are runtime errors also called?
exceptions
210
Logical errors are also called ...
... semantic errors.
211
What is the exception class? (3)
* is at the top of the hierarchy for all exceptions * base class for all exceptions * includes a number of properties that help identify the type and the cause of the exception such as: Message StackTrace InnerException
212
What is an exception class Message?
* gets a message that describes the current exception
213
What is an exception class StrackTrace?
* gets a string representation of the frames on the call stack at the time the current exception was thrown
214
What is an exception class InnerException?
* when one exception occurs as the direct result of another, the initial exception may be held in this property
215
How do you use a try-catch block for handling exceptions? (10)
* place the code that could potentially throw an exception in the tryblock * place the code to handle the exception in the catchblock * execution of the try block terminates at the statement that throws the exception * when an exception is thrown in a try block, control is transferred to the first matching catch block * a try block must be followed by at least one catch block * there can be more than one catch block (one per exception) * each catch block is used to catch one type of exception (exception filter) * ultiple catch blocks should be ordered from most specific to most general (following the inheritance-hierarchy) * if no catch block specifies a matching exception filter, a catch block with no filter will be executed * you cannot place any code between a try block and catch block or between multiple catch blocks
216
What is the finally block? (3)
* is used to perform important tasks (clean-up) and is executed regardless of whether an exception occurred or not * is an optional clause that follows the catch blocks * e.g. code to close a file or a database connection in the finally block guarantees that it is executed, independent of exceptions thrown
217
Why and how to you create custom exceptions? (3)
* you can create Custom Exception objects to address specific business rules of the problem domain by extending the ApplicationException class * programmer explicitly throws the Exception object from a method * you can throw an exception by using **throw new** statement similar to handling other Exception objects
218
Apply a try-catch block to the following code. Users shouldn't enter letters and there should be a generic exception. ``` private void btnDiv\_Click(object sender, EventArgs e) { //read input int x = int.Parse(txtNumber1.Text); int y = int.Parse(txtNumber2.Text); //calc int z = x / y; //show MessageBox.Show("Results " + z); } ```
``` try { //read input int x = int.Parse(txtNumber1.Text); int y = int.Parse(txtNumber2.Text); //calc int z = x / y; //show MessageBox.Show("Results " + z); } ``` catch (FormatException) { MessageBox.Show("please enter digits only"); } catch { MessageBox.Show("Error - try again."); }
219
How do you catch an exception, that the number the user entered is too large?
catch (OverflowException) { MessageBox.Show("Your number is too big for this calculator."); }
220
How do you catch an exception, that indicates to a user he/she must enter digits only?
catch (FormatException) { MessageBox.Show("Please enter digits only."); }
221
How do you handle an exception that a user should not try to divide by zero?
catch (DivideByZeroException) { MessageBox.Show("Cannot divide by zero!"); }
222
Instantiate a list.
List CollName = new List();
223
jj
``` //how many items in myFaveThings //MessageBox.Show(myFaveThings.Count.ToString()); ```
224
hh
//Iterate string allItems = ""; foreach(object item in myFaveThings) { allItems += item + ","; } //MessageBox.Show(allItems);