C# Flashcards Preview

Cert IV Programming > C# > Flashcards

Flashcards in C# Deck (224):

What is a variable?

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


What parts does a variable have? (5)

  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


List the 5 different .NET data types.





built-in reference


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

string and object


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

  • System.Byte - byte
  • System.Int16 - short
  • System.Int32 - int
  • System.Int64 - long
  • System.SByte - sbyte
  • System.UInt16 - ushort
  • System.UInt32 - uint
  • System.UInt64 - ulong


C# byte data type

8 bit, unsigned, 0 to 255


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

signed, 16 bit, -32768 to 32767


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

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


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

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


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

8 bit, signed, -128 to 127


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

16 bit, unsigned, 0 to 65535


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

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


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

64 bit, unsigned, 0 to2^64-1


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

  1. System.Single - float
  2. System.Double - double
  3. System.Decimal - decimal


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

- 32 bit - 7 significant digits - +/-1.4 x 10^-45 to +/-3.4 x 10^38


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

- 64 bit - 15 - 16 sign. digits - +/-5.0 x 10^-324 to +/-1.7 x 10^308


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

- 128 bit - 28 sign. digits - +/-1.0 x 10^-28 to +/-7.9 x 10^28


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



What values can Boolean take on?

only true and false


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

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


What is the use of a string data type?

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


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

  • Char values are enclosed in single quotes.
  • String values are enclosed in double quotes.


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

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


How do you assign an object to the object type?

object myObject;

myObject = 543

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


When do implicit conversions happen in C#?

- automatically performed whenever conversion can be performed without loss of data


Code an implicit conversion of a variable storing the number 100 into 64 bit.

int SomeNumber = 100;

long LongVariable;

LongVariable = SomeNumber;


What is an explicit conversion also called?

a cast


Give a generic example of an explicit conversion of a chosen number.

int someInteger = 22

short someShort;

someShort = (short)someInteger;


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


Give a simple example for a Parse conversion of a string '123456'.

int I;

string S;

S = "123456";

I = int.Parse(S);


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)


Which comparison operators does C# know?

/* relational: < > <= >=

equality: == != */


What logical operators does C# know? (5)

  • logical AND ("&amp;")
  • logical OR (|)
  • logical XOR (^)
  • conditional AND ("&amp;&amp;")
  • conditional OR (||)


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


Microsoft Visual Studio is the main ... (IDE) from Microsoft.

Integrated Development Environment


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


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


Can you mix and match Frameworks and Visual Studio Editions?



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


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


Windows apps require ... Windows apps provide a consistent ... (...) for communicating with drivers, devices, and so on.

a Windows Runtime Environment, API (Application Programming Interface)


.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


What are the 2 components of .NET Framework?

Framework Class Library (FCL) [here Base Class Library]


Common Language Runtime (CLR)


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


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


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


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


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


What is IL code?

~ low level language designed to be read and understood by the CLR


What is a runtime?

~ the period of the program lifecycle phase during which a computer program is executing


What is "unmanaged code"?

~ refers to programs written in C, C++, and other languages that do not need a runtime to execute


Who developed C#?

Anders Hejlsberg and his team during the development of .Net Framework.


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


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


Conditional Compilation

Simple Multithreading

LINQ and Lambda Expressions

Integration with Windows


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


What is a namespace?

~a collection of classes


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.


What is the entry point for all C# programs?

the Main method


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


What do you use an if-statement for?

-use to make a single-alternative decision

-use it to determine whether an action will occur


What is the general structure of an if-statement?

if (testedExpression)



-testedExpression is any expression that evaluates as true or false
-statement represents the action that will take place if the expression evaluates as true


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


What is the format to execute more than one statement in an if-statement?

Use curly brackets!

if (hoursWorked > FULL_WEEK) {

regularPay = FULL_WEEK * rate;

overtime = (hoursWorked – FULL_WEEK) * OT_RATE * rate;



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.


What is the format to code dual-alternative if decisions?

if (testedExpression) 




Else without if is illegal!


What are nested if statements?

~statements in which if structure is contained inside of another if structure


When do you use nested if statements?

-when two conditions must be met before some action is taken


Explain the decision making process in the following code:


if (saleAmount > 1000)

if (saleAmount < 2000)

bonus = 50;


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


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


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


What happens if you use the assignment operator in a testedExpression instead of the equality operator?

if (number = 3)




-will produce error


What happens if you place a semicolon right after the testedExpression in an if statement?

if (testedExpression) ;


-testedExpression has no action

-statement will execute independently of the testedExpression



What types of loops exist?





One execution of any loop is called an ...



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


What is the syntax of a while loop?

while (Boolean expression)

 loop body;


What is a loop called that executes a specific number of times?

A definite loop or a counter controlled loop.


What is the general syntax of a counter controlled loop?

Loop control variable = a

Limiting value = B

int a;

const int B = 11;

a = 1;

while (a < B) {


a = a + 1;



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


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


How do you exit an infinite loop?

with Ctrl-C or Break


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)




Infinite loops are commonly used in ...

... data input validation / testing.


When is a for loop commonly used?

Is used when a definite number of iterations is required.


Give the general syntax of a for loop.

for (initialise; evaluate; alter)

loop body;



for (int a = 1; a < 5; ++a)



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


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);


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.


What is the syntax of a do-while loop?

do {

loop body;


while (Boolean expression);


What is another name for the do-while loop?

posttest loop


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


What are nested loops?

~ When you place another loop within a loop.


A loop that completely contains another is an ...

... outer loop.


A loop that falls entirely within the body of another is an ...

... inner loop.


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


Code: Print 3 mailing labels for each of 20 customers.

for (customer = 1; customer <=20; ++customer)

for (label = 1; label <= 3; ++label)


print statements;



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


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


while (x < a + b)  --> sum = a + b;

                                       while (x < sum);


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


while (A || B)  --> swap if B more likely --> while (B || A)


How do you make a comparison to 0 to improve loop performance?

  • improves performance if you compare to 0 rather than to another value


a test from upwards from 0 to 1000 is slower than downwards from 1000 to 0


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


for (int i = 0; i < 40; ++i)


for (int i = 0; i < 40; ++i)


AS for (int i = 0; i < 40; ++i) {





What is an array?

A way to store multiple variables of the same type.


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


How do you declare and instantiate an array?

variable type[] variable name

variable name = new variable type[size];



int[] x

x = new int[4];


Declare and instantiate an array in one line.

int[] numbers = new int[4];


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;


Initiate and declare an array called "numbers" including its' values, 44, 2, 39, 11.

int[] numbers = new int[4] {44, 2, 39, 11};


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


 Fill in the following blanks according in order of the red numbers given.


Q image thumb

  • 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


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] + ",";




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


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


Programmers refer to information about the problem they are solving as ...

... the problem domain.


What is OOP?

= Object-Oriented Programming

  • is a technique for managing problem complexity by defining objects from the problem domain


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


What is a class?

  • = a blueprint for an object
  • defines the common characteristics, e.g. every car has wheels, brakes


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


Give the simplified structure of a class and it's elements.

public class ClassName








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


Declare 3 fields for student ID, student first name, and student last name.

private int studentId;

private string firstName;

private string lastName;


Declare the properties for an attribute eye colour.

public string EyeColour


get {return eyeColour;}

set {eyeColour = value;}



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


Give another name for creating objects.



What is a null constructor? Give it's syntax.

  • if no other constructor has been explicitly declared the compiler inserts one:


public Name()




Create an object for a new student, s1.

Student s1 = new Student();


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;


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


What do methods roughly consist of? (3)

  • meaningful name to describe the task
  • required information to complete a task
  • result of task completion


What are method arguments?

  • the information required to complete the task
  • can require zero, one, or several arguments


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


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;


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


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


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


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


How is data stored in the RAM? (3)





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


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


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


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


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


What is overloading?

= when two or more methods (including constructors) are defined in the same class and given the same name


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


What are enumerations?

=user-defined sets of integral constants that correspond to a set of friendly names


How do you declare an enumeration? (4)

  • is declared before class declaration, as follows

public enum NameEnum

  • 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;




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


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


What class is the root of all classes?

the Object class


Define Monkey as the sub class of Animal.

public class Monkey : Animal




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;


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


How do you override base class members?


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


How do you override the following scenario?

Base class: Animal, Animal moves

Subclass: Monkey, monkey jumps


public class Animal {

public virtual string Move() {

return "Animal moves";



public class Monkey : Animal {

public override string Move() {

return "Monkey jumps";





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


How do you hide the following base class method?

Base class: Animal, Animal moves

Subclass: Monkey, monkey jumps


public class Animal {

public string Move() {

return "Animal moves";



public class Monkey : Animal {

public new string Move() {

return "Monkey jumps";




List the existing access modifiers? (5)





protected internal


From where can you access a member with the access modifier "public"?

  • can be accessed from anywhere


From where can you access a private member?

  • can only be accessed by members within the class that defines it


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


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


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


What types of collections exist and what is their respective namespace?

System.Collections namespace
System.Collections.Generic namespace


List the types of non-generic collections. (7)

  • ArrayList
  • Stack
  • Queue
  • Hashtable
  • SortedList
  • Dictionary
  • SortedDictionary


What is an ArrayList?

  • a simple resizable,index based collection of objects
  • similar to a single-dimensional array that you can resize dynamically


What is a Stack (collection)?

  • a LIFO collection of objects


What is a Queue?

  • FIFO collection of objects


What is a Hashtable?

  • a collection of name/value pairs of objects that allows retrieval by name or index


What is a SortedList?

  • a sorted collection of name/value pairs of objects


What is a Dictionary?

  • a set of keys and their associated values


What is SortedDictionary?

  • to maintain the collection in order by the key


What is the namespace of non-generic spezialised collections?



What types of non-generic spezialised collections exist? (4)

  • BitArray
  • StringCollection
  • StringDictionary
  • NameValueCollection


What is a BitArray?

  • a collection of boolean values


What is a StringCollection?

  • a simple resizable collection of strings


What is a StringDictionary?

  • a collection of name/values pairs of strings


What is a NameValueCollection?

  • a collection of name/value pairs of strings that allows retrieval by name or index


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


List the types of generic collections that exist. (5)

  • Generic Dictionary
  • Generic List
  • Generic Queue
  • Generic Stack
  • Generic LinkedList


What is a Collection Interface?

  • allows a collection to support a different behaviour


List types of collection interfaces. (8)

  • IComparable
  • ICollection
  • IList
  • IComparer
  • IEqualityComparer
  • IDictionary
  • IEnumerable
  • IEnumerator


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


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


What does the collection interface IList do?

  • provide a common way to add/remove items


What does the collection interface IComparer do?

  • exposes a method that compares 2 objects


What is the function of IEqualityComparer?

  • defines methods to support the comparison of objects for equality


What does the collection interface IDictionary do?

  • represents a non-generic collection of key/value pairs


What is the function of IEnumerable?

  • exposes the enumerator, which supports a simple iteration over a non-generic collection


What is IEnumerator there for?

  • supports a simple iteration over a non-generic collection


How do you add a value to a collection?

Add method /  at the end:


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");


How do you remove a value from a collection? (3)

Remove method /  specific value:


e.g. myCollection.Remove("burgers");

e.g. myStudents.Remove(new Student(2, "Bob"));

-> requires overriding Equals method!!

RemoveAt method / from specific position:


e.g.  myCollection.RemoveAt(2);


How do you empty a collection?



How do you determine the index of a particular item in a collection?


e.g. MessageBox.Show(myCollection.IndexOf("programming").ToString());


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!!


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


How do you sort through a collection?


Note: Sort for generic collection objects requires implementation of CompareTo method
            from IComparable!!


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);


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


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


What is an interface?

  • are abstract classes that define abstract methods


What is the purpose of an interface?

  • to provide a mechanism for a subclass to define behaviors from sources other than the base class


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


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


Error handling is ...

... the way of coding to handle error conditions that may arise during the runtime of the program.


Exceptions are ...

... any unexpected or exceptional situations that occur when a program is running.


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 ...



unexpected user input



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


What are runtime errors also called?



Logical errors are also called ...

... semantic errors.


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:






What is an exception class Message?

  • gets a message that describes the current exception


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


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


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


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


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


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);
                int z = x / y;
                MessageBox.Show("Results " + z);

        try {
                //read input
                int x = int.Parse(txtNumber1.Text);
                int y = int.Parse(txtNumber2.Text);
                int z = x / y;
                MessageBox.Show("Results " + z);

catch (FormatException)
                MessageBox.Show("please enter digits                      only");

                MessageBox.Show("Error - try again.");


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.");


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.");


How do you handle an exception that a user should not try to divide by zero?

  catch (DivideByZeroException)
                MessageBox.Show("Cannot divide by zero!");


Instantiate a list.

List CollName = new List();



//how many items in myFaveThings



            string allItems = "";
            foreach(object item in myFaveThings)
                allItems += item + ",";