Tagged: C Toggle Comment Threads | Keyboard Shortcuts

  • jalves61 4:53 pm on April 1, 2020 Permalink | Reply
    Tags: C   

    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.



  • jalves61 11:23 pm on March 31, 2020 Permalink | Reply
    Tags: C   

    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.

  • jalves61 6:14 pm on March 19, 2020 Permalink | Reply
    Tags: C   

    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.

  • jalves61 6:04 pm on March 10, 2020 Permalink | Reply
    Tags: C   

    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.


  • jalves61 2:51 pm on March 9, 2020 Permalink | Reply
    Tags: C   

    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.

  • jalves61 9:26 pm on March 8, 2020 Permalink | Reply
    Tags: C   

    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:


  • jalves61 10:10 pm on March 7, 2020 Permalink | Reply
    Tags: C   

    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.

  • jalves61 9:22 pm on March 6, 2020 Permalink | Reply
    Tags: C   

    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.


  • jalves61 9:02 pm on March 5, 2020 Permalink | Reply
    Tags: C   

    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.



  • jalves61 6:06 pm on February 27, 2020 Permalink | Reply
    Tags: C   

    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.

Compose new post
Next post/Next comment
Previous post/Previous comment
Show/Hide comments
Go to top
Go to login
Show/Hide help
shift + esc