Object Oriented Programming and C#: Dictionaries/Hash Tables

A “dictionary” in C# is a ADT (Abstract data type) that maps “keys” to “values”. Normally with an array, the values within this collection of data are accessed using indexing. For the dictionary, instead of indexes there are keys. Another name for a dictionary is a “hash table”, although the distinction can be made in the sense that the hash table is a non-generic type and the dictionary is of generic type. The namespace required for dictionaries is the “System.Collections.Generics” namespace.

The dictionary is initialized much like a list (dynamic array), however the dictionary take two parameters (“TKey”,”TValue”). The first is the data type of the key and the second the data type of the value. Similarly to dynamic arrays, values can be added to the dictionary using a “Add(key,value)” command. Similarly, a value can be deleted using the “Delete(key)” command. However it is important to note that keys do not have to be integers, unlike an index. They can be of any data type imaginable. However, a dictionary cannot contain duplicate keys.

The functionality of a dictionary in C# is similar to a physical dictionary. A dictionary contains words and their definitions and analogously, a programming dictionary maps a key (word) to a value (definition).

The following program illustrates adding values to a dictionary. The key is of type integer and the value of type string. The values “one”, “two” and “three” are added with corresponding integer keys.


Much like with arrays, a “foreach” statement can be used to iterate over all the values of a dictionary.


It is important to note for a hash table, the relationship between the key and its value as that this must be one to one. When different keys have the same hash value, a “collision” occurs. In order to resolve the collision, a link list must be created in order to chain elements to a single location.

An important concept with hash table: speed of processing does not depend on size. For arrays, in order to find a specific value a linear search must be performed. This takes a long time to complete if the array is very long. With a hash table, size does not matter because the hashing function is a constant time. The “ContainsKey()” method can be used to find a specific key without the need for a linear search.

When would you use a dictionary/hash table over a list? Dictionaries can be helpful in instances where indexes have special meaning. A particular use of a dictionary could be to count the words in a text using the “String.Split()” method and adding each word to the dictionary. In this instance, the “foreach” statement could easily be used to iterate over every value and find the number of words. In short, the dictionary maps meaningful keys to values whereas the list simply maps indexes to values.

Object Oriented and C#: Quadratic Roots Program

The following program is designed to accept three doubles as inputs and prints the roots of a quadratic, whether complex or real. If a non-double is inputted into the program, the program should display “Bad Input”. The program contains two files: a “program” file to run several of the main methods and a “complex” file which creates the class for handling complex numbers and overrides the built in “ToString” method.

The first goal is to initialize the part of the program that handles real roots. The easiest portion is to create a method that reads doubles. It is important that the method contains a nullable type because the method should return null if a non-double such as a string is put into the method. This provides an easy way to use a conditional statement upon using the “Tryparse” method. The “Tryparse” method returns a boolean value of true or false. The “if” statement checks if the return is true and if so, returns the result. If not, null is returned.


Next, the “getquadraticstring” method is implemented to format the printed result in the form “AX^2+BX+C”. This is also done within the “program” file. Format specifiers are put within the placeholders to set the printed values to two decimal places if neccessary.


The “getrealroots” method produces the roots of the quadratic given that they are purely real. First the discriminant (the part in the quadratic formula under the square root symbol) is calculated. Several if statements are provided to check how many real roots there are and returns that quantity as an integer. For example, if the discriminant is negative, there will be no real roots returned. This means both of the “out” variables should be set to null and the function should return a 0. For a discriminant = 0, the quadratic formula reduces to -B/2A and the second root should be null. The return value is again the number of roots (1). It is important to note that an “if-else” statement must only end in “else” rather than “else if”. The “else” statement must cover all other possibilities.


Within the “main” function, three numbers are taken from the console using the getDouble method. An integer value is obtained from the getRealroots method which states the number of roots. This will be used for the conditional statements. For ease of reading code, a string variable is created to store the return from the “getQuadraticString” method.

Next, an “if” statement is used to print a bad input if any of the a, b, c variables are null. A return statement is included within the “if” statement so that an else does not have to be provided. This will exit the statement after it has completed.


Now the logic for the imaginary numbers must be implemented. The default constructor is shown with default inputs of zero. It doesn’t need any code within it because it inherits the Complex constructor. The “ToString()” method must be overridden because the formatting must be changed to adhere to complex numbers.


In addition, logic must be implemented for the “getImaginaryRoots()” method. The discriminant is calculated the same way as before, however the absolute value is taken. The real part must be calculated separately and the denominator is split for this reason. For clarification, this is the real part of a complex root. The two roots are the same, but complex conjugates.


The “main” function must be updated to reflect the imaginary roots.


The “getQuadraticString()” method is updated as shown. Three pieces of string must be created with several conditions imposed. They begin as empty strings and are filled in. Separating them into parts lets the logic be implemented for when each coefficient is 1 or -1. When C is zero, an empty string will be printed.



Object Oriented Programming and C#: Program to Determine Interrupt Levels

The following is a program designed to detect environmental interrupts based on data inputted by the user. The idea is to generate a certain threshold based on the standard deviation and twenty second average of the data set.

A bit of background first: The standard deviation, much like the variance of a data set, describes the “spread” of the data. The standard deviation is the square root of the variance, to be specific. This leaves the standard deviation with the same units as the mean, whereas the variance has squared units. In simple terms, the standard deviation describes how close the values are to the mean. A low standard deviation indicates a narrow spread with values closer to the mean.


Often, physical data which involves the averaging of many samples of a random experiment can be approximated as a Gaussian or Normal distribution curve, which is symmetrical about the mean. As a real world example, this approximation can be made for the height of adult men in the United States. The mean of this is about 5’10 with a standard deviation of three inches. This means that for a normal distribution, roughly 68% of adult men are within three inches of the mean, as shown in the following figure.


In the first part of the program, the variables are initialized. The value “A” represents the multiple of standard deviations. Previous calculations deemed that the minimum threshold level would be roughly 4 times the standard deviation added to the twenty second average. Two arrays are defined: an array to calculate the two second average which was set to a length of 200 and also an array of length 10 for the twenty second average.


The next part of the program is the infinite “while(true)” loop. The current time is printed to the console for the user to be aware of. Then, the user is prompted to input a minimum and maximum value for a reasonable range of audible values, and these are parsed into integers. Next, the Random class is instantiated and a for loop is incremented 200 times to store a random value within the “inputdata_two[]” array for each iteration. The random value is constrained to the max and min values provided by the user. The “Average()” method built into the Random class gives an easy means to calculate the two second average.


Next, a foreach statement is used to iterate through every value (10 values) of the twenty second average array and print them to the console. An interrupt is triggered if two conditions are met: the time has incremented to a full 20 seconds and the two second average is greater than the calculated minimum threshold. “Alltime” is set to -2 to reset the value for the next set of data. Once the time has incremented to 20 seconds, a twenty second average is calculated and from this, the standard deviation is calculated and printed to the console.


The rest of code is pictured below. The time is incremented by two seconds until the time is at 18 seconds.


The code is shown in action:


If a high max and min is inputted, an interrupt will be triggered and the clock will be reset:


Object Oriented Programming and C#: Fractions Program

The following is a post explaining the functionality of a C# program in Visual Studio, which is designed to do basic operations between fractions which are ratios of whole numbers.

To begin, three namespaces are included using the “using” directive statement.


The “system” namespace is included with every program. The next two must be included to implement certain classes. Without the directives in place, these namespaces would have to be included manually with every usage of the classes that are a part of them.


The next bit of code is pictured above. Two integers are created with a “private” access modifier to indicate they can only be used within the Fraction class. Next, the constructor for Fraction is called and supplied with the two integers. The “this” keyword uses the current instance of the class to assign one of the inputs (num) to a member of the class. “This” can be helpful to distinguish between constructor inputs and members of the class since “this” always refers to members of the current instance. An “if” statement is included to handle exceptions thrown by having a denominator of zero. You can always identify a constructor by its lack of a data type.


For some reason, the constructor should be called again, and it should inherit itself (???) with a 0 and 1 supplied as its argument. God only knows why.


The Reduce function is meant to reduce the fraction to its canonical (simplest) form. It is important to note that the method is private, which means that it cannot be used outside the class “Fraction”. The greatest common denominator is initialized to zero. A for loop is executed to cycle through all the way to what “denomenator” is used for. Denomenator is allowed to be used here because the method is used within the class. Successive division is used to check if the canonical form has been achieved. By dividing by the loop index and checking for a remainder of zero for both the numerator and denominator, it can be shown whether more division should be done or not. If both conditions are true, the greatest common denominator has been found to be the loop index. The next step is to divide the numerator and denominator through by this value. For example, if the numerator was set to 3 and the denominator was set to 6, by the time the loop counter reached three, both statements would return a boolean “TRUE” and the gcd would be set to 3. Then both values would be divided by 3, reducing the fraction to 1/2.


The next step is to define the properties. Properties allow private variables to be used publicly. This can be useful when you need to protect certain data by not allowing it to be used in any class, but sometimes needs to be exposed. This is accomplished using “getters” and “setters”. The “value” keyword is automatically provided when using a “setter” and sets the private variable to that value. Basically, numerator and denomenator are private variables and can only be changed within the class. Encapsulation refers to the scope of members within classes or structs. Properties provide a flexible way to control the accessibility of these members.

The last method is used to convert integer fractions to the double data type. This functionality is provided by the “explicit” keyword. The result is a returned “fractiondecimal” of data type double.


The following codes are suppressed using the “#region” keyword. By entering each region, the code can be viewed. Within the first block of code, the custom arithmetic operators are defined, two of which are shown below.


The addition is slightly complicated, because a common denominator must be found. Different implementations of the Fraction class are supplied to the input of the operator method. The fields “numerator” and “denomenator” are accessed through the class and assigned to a variable. A new object (“c”) is instantiated from the Fraction class which is the sum of “a” and “b”. The multiplication custom operator is slightly simpler, because it is straight across multiplication. Additional code is provided to change the sign of both the numerator and denominator if the denominator is negative. The operators for division and subtraction employ similar logic.

The comparison operators are defined using the same common denominator technique. The only difference between each operator method is the symbol used in the “if” statement. Six methods are provided (<, >, ==, !=, >= and <=).


The last bit of code is pictured below. The “ToString” method is inherited by every class and therefore can be overridden. This allows flexibility to define the “ToString” method however you want. In this case, we want a fraction to be printed. The “as” keyword can convert between nullable or reference types and returns null if the conversion is not possible. When this conversion from obj to Fraction is possible, the numerator and denominator are set and the fraction is returned.


Object Oriented Programming and C#: Simple Program to add three numbers

The following is a simple program that takes a user input of three numbers and adds them but does not crash when an exception is thrown (eg. if a user inputs a non integer value). The “int?” variable is used to include the “null” value used to signify that a bad input was received. The user is notified instantly when an incorrect input is received by the program with a “Bad input” command prompt message.


The code above shows that the GetNumber() method is called (shown below) three times, and as long as these are integers, they are summed and printed to the console after being converted to a string.


The code shows that as long as the sum of the three integers is not equal to null (anything plus null is equal to null, so if at least one input is a non-integer this will be triggered) the Console will print the sum of the three numbers. The GetNumber() method uses the “TryParse” method to convert each string input to an integer. This will handle exceptions that are triggered by passing a non-integer to the command line. It also gives a convenient return of “null” which is used above.

The following shows the effect of both a summation and an incorrect input summation failure.



Object Oriented Programming and C#: Shallow vs Deep Copying

The following will be a brief but important post illustrating the difference between reference and value types. In C#, value types are things like integers, floats, enumerations and doubles. A value type holds the data assigned to it in its own memory allocation whereas a reference type only holds an address which points to the actual data. A reference type is anything that is not an int, float or double, etc such as a dynamic array (list), static array, class objects, or strings. It is important to know the difference because when code such as the code below is executed, it can have some confusing effects.

shallow copy

The image above illustrates what is known as a “shallow copy”. Because instances of classes are not storing actual data but are used as pointers, when the object is copied to the second object, the memory address is copied instead of the data contained within “obj”. Therefore, any changes made to “obj2” will also affect “obj” because they point to the same data. The following image shows the difference between deep and shallow copies.


To do a deep copy of an array, for instance, every element of that array must be copied to the new array. You can do that using the “Array.Copy(source array, copy array)” method. As shown in the image, this will create two references and two data instead of 2 references pointing to the same data. Shallow copying only copies a memory pointer.

Object Oriented Programming and C#: Methods

Methods in C# are quite similar to functions in C. A function is something that takes input parameters and returns outputs. The major difference between methods, which are involved with object oriented programming, and functions is that methods are associate with objects. Methods give the programmer a huge advantage in the sense that their code is much easier to read and allows the user to reuse code to avoid repetitions. It is important to note that methods can only be contained within classes and methods declared within methods are not allowed. The method “Main” is included in every program.

The following is the syntax for a method:


The return type for “main” is void since it does not return a value. The name of the method and list of parameters are called the “method signature”. The name of the method should contain either a verb or a noun and a verb. An “access modifier” gives the compiler information about how the method can be used, just as with classes. Examples are public, private, etc. The “static” method is a method that does not need to be instantiated.

“Local variables” are variables defined within a method that can only be used within the method. The area of visibility for this variable is from where it is defined to the last bracket of the method body.

Methods can be called from the “main” method or from some other method. In fact, methods can call themselves (this is called recursion). You can also call a method BEFORE it is declared!

A method’s parameters are the inputs necessary to complete whatever task the method needs to achieve. Arrays can be used as parameters if necessary. When declaring a method with parameters, the values in the parentheses are called parameters, but when the method is called, the values actually used are called arguments.

Another important note is that when a variable is passed to a method argument, the value is copied to the parameter for use within the method. However, when a variable is declared within a certain method and then placed as an argument to a method, if the parameter is hardcoded within that method, it will use the hardcoded value but the variable declared will not be effected. Here is an example:



This will print the number 5 (not 3). In the Main() method, however, numberArg is 3.

Object Oriented Programming and C#: Exception Handling

Excepting handling is a way to anticipate errors during the code writing process. An exception is a runtime error  which happens when the program is executed. A “try” block is used to section off code that may cause an exception to occur. “Catch” blocks are used to handle these exceptions. A “finally” block will run regardless of whether an exception is triggered from the “try” block. A “try” block can be implemented along with a “catch” block, both a “catch” and “finally” block, or just a “finally” block.

In the following code, an equation is coded to divide by zero, prompting an error. The suspect code is encased within the “try” block.


The Exception class is used to generate the error message (“Error is: Attempting to divide by zero”). When the code below is run (with the value of x changed), no error message is displayed, but the code within the “finally” block is run regardless of any condition. If x is changed back to zero, the same error message appears.


Object Oriented Programming and C#: Interfaces

Interfaces are a vital subject to explore within object oriented programming. An interface contains definitions for a group of related functionalities that a class or struct can implement. The interface essential defines the “what” of the contract of the classes that inherit the interface abide by. The classes perform the “how” part of the contract. The general syntax for defining interfaces is to use to “Interface” keyword and then begin the name of the interface with a capital “I”. Every class that inherits properties from the interface must contain whatever method is in the interface. The methods defined in an interface cannot have a definition, only the declaration of the method.

In the following section of code, an interface named “IDogCommands” is initialized. When a class attempts to inherit the interface, an error is given because the methods initialized within the interface are not used within the class.


An important application of implementation of interfaces in C# comes from the fact that multiple inheritance is not supported. Another is inheriting with a struct, which does not support inheritance directly. An important note is that an interface never includes implementation, only empty methods that serve as a signature. The implementation is done in the classes themselves. Interfaces can contain methods, properties, events, indexers, or any combination of those four member types.

As shown below, interfaces can even inherit from other interfaces. However you cannot instantiate an interface directly.


The distinguishing features between abstract classes and interfaces are that abstract classes do not allow multiple inheritance and can contain access modifiers and variables (interfaces cannot). Additionally, abstract classes can contain implementations of methods, which as discussed, interfaces cannot.

Object Oriented Programming and C#: Cars Exercise

The following C# program will incorporate many different aspects of object oriented programming into one assignment. The idea is to create one base class and one subclass. Within both of these classes, a method called “DisplayInfo()” is created which will be overwritten for the child class. The three variables within the method are shown at the bottom. Different access modifiers are used to define the scope or range for each variable.


The following code snippet shows the parent class “Cars” with the three variables. The method DisplayInfo() is defined as a virtual method so it can be overridden in the Mercedes class. The Mercedes class inherits the properties from the Cars class. The “base” keyword is used to access the “Cars” class properties. It is important to note that at this point, the price variable cannot be seen within the Mercedes class, so a property must be initialized.


The following code allows the price variable to be seen by the child class.


The following code displays the original variables initialized in the base class, then resets the variables to new values and displays those. The “price” variable is showing an error because the property “Price” must be used in its place.


The result:


Objected Oriented Programming and C#: Enumerations

Enumerations are lists of named integer constants. They are defined in a similar manner to classes, but instead function as lists that assign an integer a name that can be used to reference it.


When the following code is implemented, the console will display “Friday” then “4” on the next line. The first instruction tells the console to display the string placeholder for the integer and the second line displays the actual integer value from the list. Even if no direct assignments are made, the members of the enumeration have default integers assigned to them. By default, the first integer is 0 and this increments by one for every member of the list. The members of the list can be used with methods to convert to other types such as to a string, as shown.


The built in method “ToString()” is used to create a string based on the member “Monday” of the enumeration “WeekDay”.

The main purpose of enumerations are to increase code readability by giving constants meaningful names. The first constant value can be set to a specific value. If no other assignments are made, the list will automatically increment.


The code above will display “10” and “14” for example.

Object Oriented Programming and C#: Partial Classes

The “partial” keyword can be used in C# to create partial classes. These are classes that split the functionality of a single class into multiple files which are combined into a single file when the program is compiled. The following image conveys the basic idea behind a partial class. The main class is called “Geeks” which has two partial classes which individually contain a different function of the main class.


With partial classes, a method that is created in one file can be used in another. It is effectively splitting the use of one class into multiple files. This can be helpful if the class is too large to effectively or when a class that should not be modified needs additional information added to it. The following code snipped shows a method (“GetName”) being executed which exists in a separate file.


Object Oriented Programming and C#: Nested Classes

If you have spent enough time writing computer programs, you have most likely come across a situation in which you needed to “nest” a function inside a function. With object oriented programming, this can also be done with classes, as shown below.


As shown, the classes “Dogs” and “Cats” are nested inside the class “Animals”. Normally, a class is placed within the namespace, but a nested class is defined within another class. Nested classes have special privileges to objects defined from the parent class. Generally the nested class is not meant to be used on its own but is usually used when a special relationship exists between the class and its parent that requires access to private information. It is important to note that in order to access the nested class, the parent class must be referenced as well, as shown below. The nested class can be instantiated just like the parent class.



Object Oriented Programming in C# – Constructors

Object oriented programming is an entirely new perspective on programming from procedural programming. It focuses on the manipulation of objects rather than a “top-down” approach. This in general makes object oriented programs easier to modify than procedural based programs. A class is a category of objects which defines common properties of all the objects that belong to it. An object is a self contained entity that consists of data and procedures to manipulate the data.

In the following snippet of a program, a class “Person” is initialized after the class “Program”. The variables defined within the class are hidden from the parent class unless they are made public. The “perOne” is in instance of a class which is an object.


The “Firstname”, “LastName”, etc are properties of each object which are set to different strings.

A “constructor” is a method with the same name as the class, as shown by the line “Person perOne = new Person()”. The following shows the constructor for the class “Person”


If a property for “firstname” is not set, when a new object is created that property will default to “unknown” due to the constructor.