If there is one prayer that you should pray/sing every day and every hour, it is the
LORD's prayer (Our FATHER in Heaven prayer)
- Samuel Dominic Chukwuemeka
It is the most powerful prayer.
A pure heart, a clean mind, and a clear conscience is necessary for it.
For in GOD we live, and move, and have our being.
- Acts 17:28
The Joy of a Teacher is the Success of his Students.
- Samuel Dominic Chukwuemeka
I greet you this day,
For My Students, please do the following:
First: Download and install the Microsoft Visual Studio Integrated Development
Environment (IDE), or any suitable IDE for C#
Second: Review the required readings for each module including the Student-Teacher scenarios.
Third: Review the recommended readings for each module.
Fourth: Review the recommended videos and textbooks for each module.
Fifth: Complete the DB (Discussion Board) assignments for each module.
Sixth: Start thinking about your midterm project, final project, and final exam.
Seventh: Review the midterm exam and final exam study guides.
Eighth: Should you have any questions, comments, concerns, areas of improvement, and constructive criticisms;
please attend the weekly Office Hours/Live Sessions and/or contact me via the school's email system.
Ninth: If you are majoring in any IT (Information Technology) field
(especially for women and minorities),
you may want to check the Financial Aid section in any of my websites:
Scholarships or
Scholarships
For My Students and Visitors:
Comments, ideas, areas of improvement, questions, and constructive criticisms are welcome.
For All Those who Seek Peace:
Thank you for visiting.
Samuel Dominic Chukwuemeka (SamDom For Peace) B.Eng., A.A.T, M.Ed., M.S
(1.) Please review the
Rules of Netiquette
(2.) Please be creative.
Please paraphrase in your words as applicable.
(3.) No two posts should discuss the same thing.
Each post should be unique.
This implies that you should review any previous posts before you submit your own post.
(4.) The initial post is due on Thursday of the week for which it is required.
(5.) At least one response to the initial post is due on Saturday of the week for which it is required.
(6.) Only one thread per student is allowed.
Please do not create more than one thread.
Please respond to my comments (as applicable) in the same initial thread.
Please make any repost in the same initial thread.
Besides the Introduction DB (where I am required to welcome each student); usually, I make comments to some posts and some
responses submitted by Thursday of the week that a DB assignment is due.
If I make any comment to your initial post and/or response (submitted by Thursday); then it is very important you address any
concern in my comments.
If you do not understand my comments, please attend the Office Hours/Live Sessions and/or send an email to me and ask for
clarification.
I do not go back-and-forth (responding more than one time) to a student in DB forums.
The essence of DB forums is mainly for student communication and collaboration.
The professor only facilitates and makes few comments as necessary.
Typically, if I make any comment to your post and/or response for any DB assignment besides the Introduction DB,
it means that you need to fix some issues.
It is important you fix those issues to avoid deduction of points.
(7.) You may not do any of the same examples that I did for either a DB post or DB response.
(8.) You may do any of the questions in the Discuss tab as
a substantive post and/or substantive response.
(9.) You may make up your own substantive post and/or substantive response
if it is actually substantive.
However, in this case; it is very important you ask me for prior approval.
You may ask me during the Office Hours/Live Sessions and/or via the school's email.
(10.) You may solve the problems in the Assess tab as a DB assessment (post and response).
Questions in the Assess tab count for both DB post and DB response.
Each question in the Assess tab is to be uniquely done by only one student.
This means that it can be done by more than one student.
However, each post must be unique.
Further: For any Textbook Question:
(a.) Please submit a clear screenshot of the Question Number and the Question.
(b.) Any question from the textbook in the Assess tab should be done by only one student.
(11.) Sources must be cited accordingly.
You may use: APA (American Psychological Association) style, MLA (Modern Language Association) style, or the
Chicago Manual of Style.
(12.) Please submit clear screenshots.
For all applicable DB posts and responses, please use the Snipping Tool or the Snip & Sketch
on your computer to take clear screenshots
and trim off excess space/irrelevant information from your program code and output.
Then, use the Insert/Edit Image icon on the Blackboard editor to insert the screenshots of your code
and the output.
This is because your colleagues and I should be able to see your code and the output clearly.
Line numbers and all necessary details including the file names are also required.
You may need to increase the font size of your IDE so it is very clear.
You may need to take the screenshots of only the relevant window (the code window).
You may need to take several screenshots.
Also, please ensure you use a clear format for your writings.
Avoid any background colors in the Blackboard Editor.
(13.) Please do not submit an attachment for any DB assignment.
If you do, it will not be clicked. It will not be read. It will not be graded.
Your colleagues and I should be able to see your work directly without opening any attachment.
Any response to such post will not be counted.
Hence clear screenshots are required.
(14.) For all DB responses, please mention the first name of your colleague.
(15.) Provide a substantive response to your colleague.
A substantive response is the response that provides constructive criticism,
alternative approach that gives the same correct output, additional helpful information that will improve the post,
and the correction of any incorrect step and/or output among others.
How would you improve the initial post?
Did you find any errors in the initial post? If you do, please correct the error. Teach your colleague about the error, and
explain to him/her how to fix it. Provide screenshots as applicable.
What new knowledge can your colleague acquire from you based on your response?
Can you solve the initial post using an alternative approach that will give the same correct output?
What real-world examples/applications can you provide based on the initial post? Cite your sources accordingly.
Did your colleague learn anything meaningful from you based on your response to the initial post?
Please focus on the initial post. Do not deviate from the concept/topic in the initial post.
Do not bring up your own unrelated topic/concept.
Teach/Show your colleague something new and meaningful based on the initial post.
Write code examples as applicable, run them, and explain to your colleague.
Substantive responses should include screenshots as applicable.
(16.) Please use at least a size of 14 pt in your writings on the Blackboard Editor, and an acceptable
large font size on all your programs (IDE and output console among others).
(17.) Please proof-read your writings for mechanical accuracy errors.
Any use of "i" attracts deduction of points.
Multiple mechanical accuracy errors will lead to deduction of points.
I understand that this is not an English class. However, you are expected to write well.
(18.) Please make sure that you write comments for any program you submit.
Rule of Thumb for Comments (for academic purposes): Anyone (including those with little or no programming knowledge) should be
able to read your comments and have a basic idea of your program.
Unless written otherwise (for some questions), I am not saying you should write comments for every line of code.
I am asking you to write comments for every code block (section of code).
Do you read my comments? Of course, you should. I provide explanations in my comments.
Does it make sense? Yours should not be different.
A Computer program is a set of instructions given to a computer to perform specific tasks.
A Computer programmer also known as a coder is a person who writes computer programs.
A statement in C++ is an individual instruction of a program.
A Variable is a portion of computer memory for storing a data value.
Identifiers are unique names used to identify variables.
A string is a variable in C++ that contains a collection of characters enclosed in double quotation marks.
Object-oriented Programming (OOP) Language is a programming language that uses objects to accomplish the goals of a computer program.
An Object is anything that can be touched, seen, or used.
These include: data types (it can be used), variables (it can be used),
toolbox controls (it can be seen and used) among others.
An Object is also defined an instance of the class (when you use the class that has been
created).
Instantiation is the act of creating an object.
The Behavior of an object includes methods and events.
A Method is an action that an object can perform.
For example: The Exit button can use the $Me.Close()$ method to close an application.
In Object-Oriented Programming, methods are often called procedures
Events are the actions to which an object can respond.
For example: The Click event of the Exit button allows the button to respond to
a mouse click.
Properties are the set of attributes that determine the appearance and behavior of an object.
Access Modifiers specify the level of access classes and class members provide to other classes.
Encapsulation is the combination of fields, properties, methods, and events of an object
in a class(capsule).
In other words, keep all the data and program logic in one place.
Inheritance is the ability to create a new class that reuses, extends, and
modifies/overrides the behavior defined in another class.
The main class whose members are inherited is known as the Base class or Super class
The class that inherits the members of the main class is known as the Derived class or Sub
class
The derived class inherits members of the main class using the Inherits clause.
Abstraction is the hiding away of some details about a program so one can focus on the main
details.
For example, the $PrintForm()$ class in Visual Basic enables one to print a Windows form application at
run time (when the program is running)
There are so many details about the $PrintForm()$ class. However, that is not your concern. Your concern
is to use that class and print a form. So, those details are hidden from you.
Another example: You do not really want to know how the printer was developed. You just want to know how
to use the printer
and print your documents.
Constructors are class methods whose instructions are processed automatically whenever
the class is used to create/instantiate the object.
They are used to initialize the variables of the class.
Declared Elements are programming elements that is defined in a declaration statement.
They include: variables, constants, structures, properties, events, methods/procedures, and classes
among others.
Identifiers are the names used for declared elements such as the names of variables,
constructors, methods/functions, and classes among others.
Every element name in C# must follow these rules:
(1.) It must begin with an alphabet character ($A - Z$, $a - z$) or an underscore ($_$).
(2.) It must only contain alphabet characters ($A - Z$, $a - z$), decimal digits ($0 - 9$), and
underscores ($_$).
(3.) It must contain at least one alphabet character ($A - Z$, $a - z$) or a decimal digit ($0 - 9$) if
it begins with an underscore ($_$).
Fields/Variables are usually named in Camel casing (like the hump back of a camel) or Pascal casing.
Camel casing: Begin with a lowercase alphabet, middle is an uppercase alphabet (the hump of a camel) and
end with a lowercase alphabet such as $testScore$
Pascal casing: Begin with an uppercase alphabet, middle is an uppercase alphabet, end with a lowercase
alphabet such as $TestScore$
Class names begin with an uppercase alphabet such as $Student$
Constructors begin with an underscore and then use Camel casing such as _$testScore$
A backing store is the private variable that is assessed by a public property.
It is the same type as the property
Introductory concepts of C#: development environment, variables, decisions, looping, arrays, strings, methods, exception and event handling. Prerequisite: None.
By the end of this course, you should be able to do the following:
(1.) Demonstrate best practices for designing end-user computing interfaces.
(2.) Discuss software development methodologies.
(3.) Use a programming or a scripting language to solve a problem.
(4.) Discuss significant trends and emerging technologies and their impact on our global society.
machine language, assembly language, low level language, high level language, IDE (Integrated Development Environment), text editor, compiler, development toolchain, linker, program, header file library, white space, braces, curly brackets, semicolon, string interpolation, concatenation operator, variable, object, function, main function, integer, code, block of code, System namespace, namespace, Program.cs, class, method, console, console application, desktop application
Students will:
(1.) Download and install the Visual Studio IDE or any suitable IDE for C# programming language.
The Visual Studio IDE is highly recommended.
(2.) Discuss an overview of the C# programming langauge.
(3.) Write a simple program (Console Application) in C#
(4.) Write a simple program (Desktop Application) in C#
(1.) Textbook Chapter
(2.) Videos: C# 101 Video Series by Microsoft
(3.) C# Tutorials by Microsoft: Hello World
(4.) C# Tutorials by W3schools: From C# HOME to C# Comments
(5.) C# Tutorials by Tutlane: From C# Introduction to C# Hello World Program
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(6.) Type C# or Csharp in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(7.) Type C# or Csharp in the search bar and view/read the results.
00000 | 10011110 |
00001 | 11110100 |
00010 | 10011110 |
00011 | 11010100 |
00100 | 10111111 |
00101 | 00000000 |
Teacher: Please look at the code above.
Do you understand that code?
Student: The bunch of zeros and ones?
I have no idea what those mean.
int num1, num2, sumNum;
sumNum = num1 + num2;
Console.WriteLine(sumNum);
Teacher: What about this code?
Do you understand it?
Student: I do not fully understand it.
However, it makes much sense than the first code?
Teacher: Both codes execute the same tasks.
Ask the user to input those numbers. Add those numbers. Output the sum.
Which code is better?
Student: The second code of course.
Teacher: The first code is the machine code.
It is the machine language.
It is a low level language.
It is the language the computer understands directly without translation.
The second code is the high level language.
It is the language humans can read and understand better.
Hence, there is the need to compile or interpret the high level language to
the machine language
so that computers would do what we want them to do.
C# is one of the high level languages that we can use.
It is a compiled language.
This means that it is translated into machine language that can be understood directly by the
system.
In that regard, a set of tools are needed.
The set of tools is known as development toolchain
The core of the development toolchain are a compiler and its linker.
The best way to compile and run C# programs is to use an Integrated Development Environment
(IDE).
An IDE typically has several development tools including a text editor and tool to compile C#
programs directly.
For this course, the Microsoft Visual Studio Community Edition (it is free) is highly
recommended.
However, you may choose to use any IDE that you wish.
Here are some free IDEs for C#:
(1.) Microsoft Visual Studio
Community Edition 2019 (Windows) (Highly recommended. The only IDE used for this
course.)
We do have online compilers for C#.
The online compilers typically do not require any downloads and installs.
However, please note that all files in the project are required for your Midterm Project, Final Project, and
Final Exam.
In the case where you prefer to use an applicable online IDE, please make sure you download the completed
C# project (that includes all files).
Here are some free online compilers/IDEs for C#:
(1.) C# Online Compiler | .NET Fiddle
(2.) C# - OneCompiler
(3.) Online C# Compiler
(This one allows you to upload a file; also allows you to save your file if you
have a Gmail or Facebook account.)
using System; Console.WriteLine("THANK GOD");If we do not include the Using System, then we would have to write:
System.Console.WriteLine
in Line $18$ Console.WriteLine();
and
Console.Write();
As seen from the pictures:
Comments in the Visual Studio IDE is green in color. We shall keep it that way.
Comments in other IDEs might be different colors.
Student: Can you change the comments to display a different color?
Teacher: Yes Sir, you can.
Student: How do I do so, Sir?
Teacher: You do realize that if you change it, the change would be for all the
programs you develop with the Visual Studio IDE. It would not just be for C#. It would also be for C++.
Changing the color of comments would be applied to the entire Visual Studio IDE.
Student: I understand. How do I change the color of the comments?
Teacher: Here are the steps.
First:
Second:
Teacher: In the second picture, you can change the color by selecting from the
dropdown menu.
If you do not like the colors you see there, you can add your own custom color.
However, please leave the default color for all work done in this course.
Comments are required for any program you write in this course.
Rule of Thumb for writing comments (for academic purposes): Anyone should be able to read your comments and have
a basic understanding
of the program.
A single-line comment is denoted by two forward slashes.
A multi-line comment also known as a block comment begins with a forward slash and
an asterisk, and ends with an asterisk and a forward slash in that order.
Let us review more code examples. Study these codes, write them, observe the punctuation marks, and run them.
Save your work
Step 9
Then, exit
Step 10
We have closed the application.
The application is a Console application.
This means that we should be able to run the executable file and see the output directly in the console
window of the computer.
Let us locate the file and try to run it directly
The file to run is the executable file
It has .exe extension
If you do not see the file extension, Click the View tab and check the box: File name extensions in order
to see the file extension.
Depending on where you saved your program, you can locate it by Clicking:
Application → Application folder → bin → Debug
→ netcoreapp3.1 → Application.exe
The Application folder is where you have the solution file (Application.sln)
To get directly to your project, double-click the solution file.
But let us run the executable file. Double-click that .exe file.
What do you notice?
Student: Something came up and then disappeared.
Teacher: Let us fix that issue.
We want to be able to run our application directly and see the output in the console.
This leads us to another concept....
The Console.ReadLine method reads the next line of characters from the standard input stream.
This means that when we write it as the last code in our program, the program will not close unexpectedly when we
try to run it directly.
The program will wait to see if there is any line to read and will just keep waiting until the user presses a key to
exit the program.
Let's go ahead and add that to our program.
Just double-click the solution file (Application.sln) to open the project.
As you can see, when you run the program; the cursor is blicking on the next line. It is waiting for the user to
do something: either close the application or just press any key on your keyboard.
Go ahead and stop running the project bu clicking the Stop Debugging icon or press Shift + F5 key.
Save All.
Exit the project.
Locate the executable file and run it directly.
The Console.ReadKey() method: obtains the next character or function key pressed by the user.
We can also use the Console.ReadKey method to prevent the program from closing unexpectedly when we run it directly.
Usually, before we write this method; it is important to ask the user to press the Enter key preferably
(but you can press any key) to exit the program.
The pressed key is displayed in the console window.
Then, we write the method.
The program will then wait for the user to press any key before closing the console window.
Let's go ahead and add that to our program.
Just double-click the solution file (Application.sln) to open the project.
When you run the executable file, the program will ask you to press the Enter key to exit the program.
Once you press that Enter key (or any key), the program will be closed.
This ensures that the program is not closed unexpectedly.
The use of these methods are not required.
However:
If you choose to submit a console application for your Final Project, you are required to use the
Console.ReadLine method (my preference) or the Console.ReadKey method
I should be able to run the executable file directly and see the output in the console.
Desktop application is a Graphical User Interface (GUI) application.
Please review the Teacher-Student scenario
Student: Mr. C, why do we need to develop desktop application?
Can't we just focus on console applications?
Teacher: Desktop applications are required for several DB assessments and for your Midterm Project.
It is optional for your Final Project.
It is important you learn to develop them.
Student: But, why?
Teacher: These are the reasons:
(1.) GUIs (desktop applications) cover a significant aspect of Number (1.) of the Student Learning Outcomes of the course.
They also cover some aspects of Numbers (2.), (3.), and (4.)
(2.) You can run the executable (.exe) file of a desktop application in any Windows desktop.
You can even run it on a Mac with some changes.
Student: What are executable files?
Teacher: Good question.
When you develop a C# program such as the one we shall develop in a moment, an executable file is also
developed. It is a file that is run on your computer to execute (do) something on your computer.
When you download and install a program on your computer, it is normally seen as install.exe,
setup.exe or other "something".exe with the word, Application used to describe it.
In our case, it is going to be a standalone file with the exe extension that when downloaded in
any Windows desktop, can run when double-clicked.
Usually, you will get a warning from your computer not to download it because it can destroy your computer.
If you do not know the source/origin of the executable file, do not download it.
But in this case, we shall develop the program so we know it is safe.
When we develop the program, we need to follow these steps to locate the executable file.
Double-click: Application folder → bin → Debug
→ Application.exe
That Application.exe file is the executable file.
You can download it (no worries, it is safe), save it on your desktop, and run it on your desktop whenever
you want to.
Student: If I copy it to another desktop, will it run?
Teacher: Yes, it will run on any Windows desktop. That is the nice thing about it.
Student: Just that file?
It will run with all the functionality?
Without copying the entire folder?
Teacher: That is correct.
Click the PROJECTS tab of this website.
You will see some desktop applications done by my previous students.
You can go ahead and test them.
Student: Pretty cool.
Did you say it will also run on a Mac?
Teacher: It will run on a Mac.
However, you will need to install some software on a Mac to run it.
(3.) Assume you are working in a developing country (in Nigeria for example), you have a computer but no
internet service, and you really need to develop applications for the projects you are working on;
developing desktop applications is highly recommended in such cases because you do not need the Web/Internet
to run them. All you need is a laptop or desktop.
Student: But, I'm not working in Nigeria.
Neither do I intend to work there.
Teacher: What if you work for a multinational company and your compnay transfers you to work there?
What if you decide to join your church or organization on a charity mission trip?
(4.) Have you heard that the only thing that is not safe is anything on the Web?
Well-developed desktop applications minimizes your use of web and mobile applications, thereby minimizing cyber crimes.
There are limitations with desktop applications.
But, there are advantages too.
At least they are much better than console applications.
Usually, you may need to download some programs to run console applications.
If you review the PROJECTS (console applications) done by my C++ students, it may require some program downloads to run on
your machine (laptop/desktop).
But the VB desktop applications and the
C# desktop applications will run without any additional download.
One of the advantages of C# is the developement of Desktop applications.
Let me welcome you, my dearest students with a desktop application. 😊
As is the case for development of desktop applications, the three basic things to do are:
(1.) Create the user interface
(2.) Set the properties.
(3.) Write the program code.
Form
In the Properties window:
(1.) Change the background color of the form to Khaki
Click the BackColor property
Click the Web tab and select Khaki color
(2.) Change the FormBorderStyle property to Fixed3D
(3.) Adjust the size as you see fit.
(4.) Change the Font property by clicking the ellipsis (three dots)
Font: Times New Roman
Font style: Regular
Font Size: 14
Click the OK button
(5.) Change the ForeColor property to Black
Repeat the same process as you did for the BackColor property.
Picture Box
(6.) Add a PictureBox from the Toolbox Common Controls
(7.) Change the Name property to MyPicture
(8.) Click the ellipsis (three dots) in the Property window
(9.) Import a picture and click Ok
(10.) Resize and position as you wish.
Label (You may use a RichTextBox if you wish)
(11.) Add a label from the Toolbox Common Controls
(12.) In the Properties window, change the AutoSize property to False
(13.) Expand as you wish.
(14.) Change the BorderStyle property to Fixed3D
(15.) Change the Name property to MessageLabel
Buttons
(16.) Add three buttons from the Toolbox Common Controls
(17.) Change the Text properties to Welcome Message, Clear, and Exit respectively.
(18.) Change the ForeColor properties of the buttons to Black
(19.) Change the BackColor properties of the button to White
Repeat the same process as you did for the BackColor property of the form.
(20.) Change the Name properties to MessageButton, ClearButton and ExitButton respectively.
Please review the screenshots, and study the comments and the codes.
If you want to run the executable file of this program, here it is:
Mr. C's Introduction (Desktop App)
Alternatively, you can follow these steps to publish your application.
These are steps I used for Visual Basic.NET
However, they are applicable to C#
(1.) Click the Build menu.
(2.) Click the Rebuid Solution command and make sure the Build succeeded.
(3.) Click the Clean Solution command.
(4.) Click the Clean IntroductionDesktopApp command.
Please review the steps in the screenshots.
Teacher: What do you think we should do next?
Student: Excuse me. I'm not sure.
Teacher: Imagine you did a program like this for your little child.
You do not want your child to run the program on your computer so that he/she does not mess up your computer.
What should you do if you want him/her to see it?
Student: Take a picture of it and show it to him/her.
Teacher: What other option?
Student: Print it and paste it on the wall in the bedroom.
Teacher: Yes...Print the application.
(1.) Download and install the Visual Basic PowerPacks
(2.) Open the solution file, Application.sln named Visual Studio Solution by double-clicking it.
It is recommended that you always open the solution file whenever you open already-developed C# programs.
(3.) You can view the Code window, Toolbox, and Properties window by clicking the View menu and selecting
whatever window you would like to view.
Open the Toolbox and do the following tasks.
These steps were done in Visual Studio for Visual Basic (VB) applications.
However, they are also applicable for C# applications.
Based on the last screenshot, the PrintForm control has been successfully added, but has not been enabled.
No worries, we shall use it in a minute. Read on.
(4.) Let us print the Program code and the GUI
Print the source code (to study it)
Give it a file name and specify a location for the printed page
The printed page should look like like this:
Print the Design Form/User Interface (to give to your child)
It is highly recommended you Build Solution first before you Run the solution.
Run the program
Use the Snipping Tool or the Snip & Sketch
on your computer and take the screenshot of the program (just as I did)
Then, print the user interface.
(1.) Discuss a brief history of C#.
(2.) Discuss the versions of C# including any significant change made for each version.
(3.) Discuss any console application developed with C#.
(4.) Discuss any desktop application developed with C#.
(5.) Discuss any web application developed with C#.
(6.) Discuss any mobile application developed with C#.
(7.) Discuss any IDE for C# including the advantages and disadvantages.
(8.) Explain using appropriate examples, any three new terms learned in this module.
(9.) Compare any three features of C# with any similar object-oriented language.
(10.) Contrast any three features of C# with any similar object-oriented language.
(1.) Include any missing gaps in the history of C#.
(2.) Include any missing gaps in the versions of C#.
(3.) Discuss an additional console application developed with C#.
(4.) Discuss an additional desktop application developed with C#.
(5.) Discuss an additional web application developed with C#.
(6.) Discuss any mobile application developed with C#.
(7.) Discuss any IDE for C#. Include the advantages and disadvantages.
(8.) Add to the post of the student who explained any three new terms learned in this module.
(9.) Add to the post of the student who compared three features of C# with another
object-oriented langauge.
(10.) Add to the post of the student who contrasted three features of C# with another
object-oriented langauge.
(11.) Provide any of these if it is lacking in any DB post that solved any question in the
Assess tab of this module: Well-written comments; another approach/method to solving the
question; any additional relevant details; etc.
(12.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(1.) Develop a desktop application titled: Introduction
The application should include three buttons: the About button, the Clear button, and the
Exit button.
When a user opens the application, it should display a blank page and the three buttons.
When the user clicks the About button, these information should be displayed:
(a.) Your picture
(b.) A brief summary of you. Write at least three sentences about yourself.
(c.) One sentence about the course and your major/program.
(d.) One sentence about the course expectations/accomplishments. What is your expectation about the course? What
do you intend to accomplish at the end of the course?
(e.) Any other thing you would like us to know about you.
When a user clicks the Clear button, the page should be blank.
When a user clicks the Exit button, the application should close.
I am more interested in the functionality.
However, I am also interested in the design/graphics/aesthetics.
Make a good design.
(2.) Write two different sentences on two different lines.
Insert a blank line between the first line and the second line.
Do NOT use the escape sequence.
vary, variable, identifier, data type, data value, value, parameter, container, ASCII (American Standard Code for Information Exchange), static variables, instance variables, array elements, value parameters, reference parameters, output parameters, local variables, definite assignment, assignment operator, initially assigned variables, initially unassigned variables, constant, keyword, reserved keyword, contextual keyword, access keys, tab index property, type conversion, casting, cast, implicit conversion, explicit conversion, user-defined conversion, conversion with helper classes, integral numeric data types, floating-point numeric data types,
Students will:
(1.) Discuss the meaning of variables in C#
(2.) Discuss the data types in C#
(3.) Discuss the rules for using identifiers in C#
(4.) Write C# programs involving the use of variables and data types.
(1.) Textbook Chapter
(2.) Videos: C# 101 Video Series by Microsoft
(https://channel9.msdn.com/Series/CSharp-101/?WT.mc_id=Educationalcsharp-c9-scottha)
(3.) Tutorials by W3schools: From C# Variables to C# Type Casting
(https://www.w3schools.com/cs/cs_variables.asp)
(4.) Tutorials by Microsoft - Part 1: Declare and Use Variables
(https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/intro-to-csharp/hello-world?tutorial-step=2)
(5.) Tutorials by Microsoft - Part 2: From Types to Conversions
(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types)
(6.) Tutorials by Microsoft - Part 3: C# Concepts: From C# type system to Basic Types
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/)
(7.) Tutorials by Microsoft - Part 4: C# Keywords
(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/)
(8.) Tutorials by Tutlane: From C# Data Types to C# Comments
(https://www.tutlane.com/tutorial/csharp/csharp-data-types-with-examples)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(9.) Type C# Variables and/or C# Data Types in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(10.) Type C# Variables and/or C# Data Types in the search bar and view/read the results.
A Variable is a portion of computer memory for storing a data value.
Because a variable stores a data value, it is important to identify the type of data value it stores.
This implies that any variable is associated with a data type.
The data type describes the type of data value stored by the variable.
What type of data is being stored? Are they numeric (numbers), non-numeric
(letters/characters/words), etc.?
As noted with the word: variable, any value stored by it can vary (can change).
A variable is created/declared in C# by specifying the data type associated with it and
assigning it to a value.
Generally, we declare a variable in C# this way:
dataType variableName;
OR
dataType variableName = value;
The equal sign is the assignment statement.
In other words, you assign something in C# using the equal sign.
There are seven categories of variables in C#
They are:
(1.) Static variables
(2.) Instance variables
(3.) Array elements
(4.) Value parameters
(5.) Reference parameters
(6.) Output parameters
(7.) Local variables
A data type is used to define the variable.
It tells what kind of variable is being declared.
When we declare a variable or constant in a program, we must specify the type or use the var kewyord.
The var keyword means a variable keyword. Sometimes, we use it if we do not want to associate a
specific data type with the variable.
Data types in C# language consists of: Value Types, Reference Types, and Pointer Types
Structure type (struct_type) | Enumeration type (enum_type) |
|
|
Let us discuss the Simple Types of the Value Types
Simple Data Type | Declaration | Size | Description |
---|---|---|---|
(1.) Signed Byte | sbyte | $1$ byte ($8$ bits) | Integers from $-128$ to $127$ are stored |
(2.) Byte | byte | $1$ byte ($8$ bits) | Integers from $0$ to $255$ are stored |
(3.) Short (Signed Short) | short | $2$ bytes ($16$ bits) | Integers from $-32768$ to $32767$ are stored |
(4.) Unsigned Short | ushort | $2$ bytes ($16$ bits) | Integers from $0$ to $65535$ are stored |
(5.) Integer (Signed Integer) | int | $4$ bytes ($32$ bits) | Integers from $-2,147,483,648$ to $2,147,483,647$ are stored |
(6.) Unsigned Integer | uint | $4$ bytes ($32$ bits) | Integers from $0$ to $4294967295$ are stored |
(7.) Long (Signed Long) | long | $8$ bytes ($64$ bits) |
Integers from $-9,223,372,036,854,775,808$ to $9,223,372,036,854,775,807$ are stored NOTE: End any integer declared with the long data type with an uppercase L |
(8.) Unsigned Long | ulong | $8$ bytes ($64$ bits) |
Integers from $0$ to $18,446,744,073,709,551,615$ are stored NOTE: End any integer declared with the ulong data type with an uppercase L |
(9.) Float | float | $4$ bytes ($32$ bits) |
From $\pm 1.5 * 10^{-45}$ to $\pm 3.4 * 10^{38}$ Up to $7$ decimal places are stored This means a precision of $7$ digits NOTE: End any decimal declared with the float data type with f or F |
(10.) Double | double | $8$ bytes ($64$ bits) |
From $\pm 5.0 * 10^{-324}$ to $\pm 1.7 * 10^{308}$ Between $15$ and $16$ decimal places are stored This means a precision of $28 - 29$ digits NOTE: End any decimal declared with the double data type with d or D |
(11.) Decimal | decimal | $16$ bytes ($128$ bits) |
From $\pm 1.0 * 10^{28}$ to $\pm 7.9 * 10^{28}$ Between $15$ and $16$ decimal places are stored This means a precision of $15 - 16$ digits NOTE: End any decimal declared with the decimal data type with m or M |
(12.) Boolean |
bool Boolean |
$1$ bit $0$ = false, $1$ = true Make the connection with electronic devices. $0$ = Off; $1$ = On |
Only false and true values are stored Displays as $0$ and $1$ respectively |
(13.) Character | char | $2$ bytes ($16$ bits) |
Integers from $0$ to $65535$ are stored. Only a single character/letter is stored. The single character must be enclosed in single quotes. The decimal values of ASCII characters/values are also stored. NOTE: If you intend to use the decimal values of ASCII characters/values, you must declare it with the char data type and the decimal value should not be included in quotation marks. |
Let us include one data type from the Reference Types We are including it because we shall use it in this module. |
|||
String | string | $2$ bytes ($16$ bits) per character |
A sequence of characters is stored. It must be enclosed in double quotes. |
The integral numeric data types are the: Integer, Unsigned Integer, Long, Unsigned Long, Signed Byte, Byte, Short,
Unsigned Short, and Character data types.
The floating-point numeric data types are the: Float, Decimal, and Double data types.
...
Skip Reference Types for now
...
C# variables are identified with unique names known as idenfiers.
It is important to use identifiers that are meaningful and descriptive.
Anyone reviewing your program should not have to guess the meaning of your variable.
As you can see (based on the image below: Variables, Data Types, Values:)
The variables I used in that example are meaningful and descriptive
Those variables are:
state to denote the State of Ohio, OH
numState to denote the number of the State of Ohio in an alphabetical listing of the
state names
povertyRate to denote the poverty rate of Ohions according to the $2000$ census data
landArea to denote the land area of the Ohio according to the $2000$ census data
motto to denote the motto and seal of the Great State of Ohio
isMottoTrue to denote the Boolean data type if the motto is true
Even without the comments, you already have an idea of the meaning of my variables.
I should not have to guess the meaning of your variables.
Variable names:
(1.) Can be single letters (please avoid unless if used in loops)
(2.) Can contain a combination of letters, digits, and underscores but must not begin
with a digit.
It may begin with a letter or an underscore.
It must not contain two consecutive underscores because those names are reserved for compiler generated identifiers.
Be it as it may:
(a.) Please avoid underscores
Avoid underscores even if the variable name does not begin with an underscore.
(b.) Use a combination of letters and digits such as:
num1 to represent the first number
variable1 to represent the first number
(3.) Can contain only letters but must not be any of the keywords.
C# Keywords are predefined, reserved identifiers with special meanings to the compiler.
They consist of: reserved keywords and contextual keywords
Reserved keywords have special meanings in all C# programs.
Contextual keywords have special meanings in limited C# program contexts. This means that they can be used as identifiers
outside those contexts.
As new keywords are added to the C# language, they are added as contextual keywords.
This is done in order to avoid breaking programs written in earlier versions of the language.
It is highly recommended to avoid using any keywords as an identifier in any C# program.
The reserved keywords are:
abstract, as, base, bool, break, byte, case, catch, char, checked, class, const, continue, decimal,
default, delegate, do, double, else, enum, event, explicit, extren, false, finally, fixed, float, for,
foreach, goto, if, implicit, in, int, interface, internal, is, lock, long, namespace, new, null, object,
operator, out, override, params, private, protected, public, readonly, ref, return, sbyte, sealed,
short, sizeof, stackalloc, static, string, struct, switch, this, throw, true, try, typeof, uint, ulong,
unchecked, unsafe, ushort, using, virtual, void, volatile, while
The contextual keywords are:
add, alias, ascending, async, await, by, descending, dynamic, equals, from, get, global, group, into, join,
let, nameof, notnull, on, orderby, partial (type), partial (method), remove, select, set,
unmanaged (generic type constraint), value, var, when (filter condition), where (generic type constraint),
where (query clause), with, yield
(a.) The letters can be Camel case (similar to the hump of a camel) such as:
firstVariable...the V is the hump
In Camel casing letters: two letters are merged as one; the first letter of the second word is
an uppercase letter while all other letters are lower case letters.
In firstVariable, V is uppercase; all other letters are lower case
(b.) The letters can be Pascal case such as FirstVariable
In Pascal casing, two letters are merged as one; the first letter of the first word and the
first letter of the second word are uppercase letters while all other letters are lower case letters.
In FirstVariable, F and V are uppercase; all other letters are lowercase.
(c.) uppercase letters (please avoid...it denotes someone who is yelling)
(d.) lowercase letters (okay, but try to avoid)
Student: What if you have three words?
How do you write it in Camel case? Pascal case?
Teacher: Say we want to write the variable, first arithmetic sequence
Camel case: firstArithmeticSequence...A and S are the only uppercase
Pascal case: FirstArithmeticSequence...F, A, S are the only uppercase
In this course, for all applicable variables; please use:
(i.) A combination of letters and digits such as num1 OR
(ii.) Camel case letters such as firstNumber OR
(iii.) Pascal case letters such as FirstNumber
***We shall use single characters when we write conditions for Iteration statements/Loops
because it is
easier to use single characters in such cases. We shall see examples when we discuss loops.
However, feel free not to use it if you wish.***
(4.) Can contain only letters but must not be these literals: true, false, null
(5.) Cannot contain whitespaces.
A whitespace is a horizontal or vertical space.
For example: myNum has no whitespace; but my Num has a whitespace.
Variable names cannot contain whitespaces.
Hence: myNum is acceptable, but my Num is not acceptable.
It is also highly recommended to avoid special characters in C# variable names.
Special characters are all the non-numeric and non-alphabet characters on your keyboard such
as ~ (tilde), !(exclamation), @ (asperand), # (hash), $ (dollar), % (percent), ^ (caret), & (ampersand), *
(asterisk).
For all course work, please avoid special characters in variable names.
Declaring Read-Only Variables: Use the const keyword (constant keyword)
As we have learned, a variable vary. The value changes.
However, read-only variables do not change.
Sometimes, we need these kind of variables.
We have to create/declare them using the const keyword.
For example, if we want to use the approximate value of pi as $3.142$ rather than using the
exact value, we can declare it as:
const int $piValue = 3.142$
This means that the variable, piValue is a read-only variable
It will not change it's value.
Student: May you please give code examples?
Teacher: Sure.
We shall begin with console applications.
Then, we shall develop desktop applications.
We shall create a new project and name it: Module2
Let us review these two examples.
Let us try to modify the value of the read-only variable and try to run it to see the output.
Please do not run any program that compiles with an error.
As you can see, the variable $piValue2$ cannot be changed because it was declared as a read-only
variable (using the const keyword)
Teacher: As you see: for the new value of piValue1, we can modify the value of any variable we create, by specifying another value for that same variable name.
Student: But, why do we need to do this?
Can't we just create another variable with that second value?
Teacher: Good point.
Yes, it is much better to create another variable with the new value.
However, when we work with statements and sorting techniques among others; it may be more efficient to just assign the new value to the same variable; rather than create another variable and assign the new value to it.
For example: if you are sorting through a loop also known as an iteration statement; we can create a variable, and write a conditional statement that when you compare an element in the array with the next element; assign the value of the greater element to the variable.
Rather than create a new variable, assign any greater value to the variable as you compare elements in the array.
There are some terms I just used, that we shall discuss in later modules.
(6.) Are case sensitive.
These are all different variables:
firstresult (lowercase),
firstResult (Camel case),
FirstResult (Pascal case),
Firstresult,
FIRSTRESULT (uppercase),
first_result (snake case)
strFirstResult (Hungarian notation)
Student: Hungarian notation?
Teacher: Hungarian notation is a naming convention that follows the camel case naming but in which
the name is preceded by the data type represented by a three-character ID.
str means string
Similarly, int is for integer; dec is for decimal;
dbl is for double; bln is for Boolean among others.
Variables, Data Types, Values Example: State of Ohio
byte to short byte to char byte to int byte to long byte to float byte to double short to char short to int short to long short to float short to double char to int char to long char to float char to double int to long int to float int to double long to float long to double float to double derived class to base class (Advanced C# course) ... among others(2.) Explicit Conversion (Casts): This is the conversion of a variable from a larger data type to a smaller data type.
double to float double to long double to int double to char double to short double to byte float to long float to int float to char float to short float to byte long to int long to char long to short long to byte int to char int to short int to byte char to short char to byte short to byte base class instance to derived class ... among others(3.) User-defined Conversion: This is the conversion that is performed by special methods that is defined to enable explicit and implicit conversions between custom types that do not have a base class-derived class relationship.
Convert.To (data type) method
This is a method of the Convert Class from the System namespace
It converts a base data type to another base data type.
As usual, we shall develop desktop applications that involves the use of variables and data types.
Let us develop desktop applications for the console application we did for the State of Ohio
We shall use several toolboxes.
Remember that the Midterm Project is a desktop application.
Hence, it is necessary to start getting familiar with GUI programming.
Please review the desktop application we did in Module $1$
We shall give appropriate names for our projects.
Tasks:
User Interface and Properties
Form:
Name Property: Leave as is
Text Property: State of Ohio: Labels and Buttons
BackColor Property: Web: Wheat
Font Property: Font: Times New Roman; Font style: Regular; Size: $14$; Script: Western
Toolbox | Property |
---|---|
Label $1$ (LHS) |
Name: leave as is Text: State |
Label $2$ (RHS) |
Name: StateLabel AutoSize: False Text: Delete it BorderStyle: Fixed3D BackColor: Web: White |
Copy, Paste, Adjust, Align: Label $1$ Label $3$ (LHS) |
Name: leave as is Text: Number |
Copy, Paste, Adjust, Align: Label $2$ Label $4$ (RHS) |
Name: NumberLabel |
Copy, Paste, Adjust, Align: Label $1$ Label $5$ (LHS) |
Name: leave as is Text: Poverty Rate |
Copy, Paste, Adjust, Align: Label $2$ Label $6$ (RHS) |
Name: PovertyRateLabel |
Copy, Paste, Adjust, Align: Label $1$ Label $7$ (LHS) |
Name: leave as is Text: Land Area |
Copy, Paste, Adjust, Align: Label $2$ Label $8$ (RHS) |
Name: LandAreaLabel |
Copy, Paste, Adjust, Align: Label $1$ Label $9$ (LHS) |
Name: leave as is Text: Motto |
Copy, Paste, Adjust, Align: Label $2$ Label $10$ (RHS) |
Name: MottoLabel |
Copy, Paste, Adjust, Align: Label $1$ Label $11$ (LHS) |
Name: leave as is Text: Is Motto true? |
Copy, Paste, Adjust, Align: Label $2$ Label $12$ (RHS) |
Name: BooleanLabel |
Button $1$ (RHS) |
Name: OhioButton Text: State of Ohio BackColor: Web: White |
Copy, Paste, Adjust, Align: Button $1$ Button $2$ (Middle position) |
Name: ClearButton Text: &Clear |
Copy, Paste, Adjust, Align: Button $1$ Button $3$ (RHS) |
Name: ExitButton Text: E&xit |
Select the first label on the left: the State label (Text property); hold the CTRL key on your keyboard and select all the Left
Hand Side (LHS) labels
Aligh all the LHS labels to the left
Click on an empty space in the form to deselect all the RHS labels.
Select the first label on the right: the StateLabel (Name property); hold the CTRL key on your keyboard and
select all the Right Hand Side (RHS) labels
Aligh all the RHS labels to the right
Click on an empty space in the form to deselect all the RHS labels.
Select the three buttons.
Click the Format menu, Make Same Size: Both
Click on an empty space in the form to deselect the three buttons.
Student: Mr. C
I have a question.
Why did you decide to include that symbol besides the "C" in the Clear button and the "x" in the Exit button?
Teacher: Very good question.
That symbol is known as the ampersand symbol
The underlined word is known as an Access Key
Student: What is an Access Key?
(1.) An Access Key is a key assigned to an object (toolbox control objects) by including the ampersand symbol, &
before a letter or number in the Text Property of the object.
(2.) When you run any desktop application, press the Alt key
If access keys were used in the application, you will see the underlined letter.
Any user can access the application by using a combination of the Alt key and the Access key
to select the specific object.
For example in our program: when we run the application; a combination of Alt + C clears the entries in the application.
Similarly, Alt + X combination selects the Exit button and exits the application.
(3.) Access keys are useful for those who cannot work with a mouse, or who do not want to work with a mouse.
(4.) It is important for programmers to assign access keys to objects that accept user input such as TextBoxes and to
objects that perform actions such as buttons.
It is part of Accessibility Design for people with disabilities.
The use of access keys in the Midterm Project is required.
It is important to use meaningful access keys.
(5.) Pressing the Alt key temporarily shows the accessing keys.
(6.) Access keys are not case sensitive.
(7.) Toolbox controls that cannot receive focus cannot have access keys.
(1.) Go to the Design View of the form and double click the State of Ohio button
(2.) Declare the variables
(3.) Write the code.
(4.) Alternatively, you can go to the View menu, and view Code
Then, select the OhioButton in the Code View under the Form1() dropdown list.
(5.) In the same manner, code the Clear button and the Exit button
(6.) Build Solution
(7.) Run the program.
Please view the screenshots. Study the comments and the code.
Clean up your code.
Remove unused events.
If you have any unused event in the Code window, take these steps to remove it.
Remove each event one at a time.
Remove the first one.
Go to the Design window and you will see an error.
Click the main line (the error)
The Designer window opens and the error line is indicated.
Delete that error line.
The TextBox is a Windows control that:
(1.) Accepts user input.
It accepts only the string type by default. So, if we want to use numeric types say an integer; then we need to convert the
string to an integer using the Convert.ToInt32 method or the Int32.TryParse method.
The TextBox can also be used to display user input. It displays only strings by default.
So, if we want to use the TextBox to display a numeric type say a double; then we need to include it in a string interpolation
or use the ToString() method.
(2.) Provides MultiLine editing with vertical scroll bars.
To use this feature, we have to check the box: MultiLine when we drag the TextBox into the form.
The Label
is a Windows control that:
(1.) Provides descriptive text for a control.
(2.) is also used to display the program output.
It displays only strings by default.
So, if we want to use the Label to display a numeric type say a double; then we need to include it in a string interpolation
or use the ToString() method.
The AutoSize property needs to be set to False so the label can be expanded.
In addition, I prefer to set the BorderStyle property to Fixed3D.
The Button
is a Windows control that raises an event when a user clicks it (click event).
In other words, it performs an action when clicked.
Here, we shall use the RichTextBox and the Buttons. No labels.
The RichTextBox is a toolbox control that:
(1.) Accepts user input.
It accepts only the string type by default. So, if we want to use numeric types say an integer; then we need to convert the
string to an integer using the Convert.ToInt32 method or the Int32.TryParse method.
The TextBox can also be used to display user input. It displays only strings by default.
So, if we want to use the TextBox to display a numeric type say a double; then we need to include it in a string interpolation
or use the ToString() method.
(2.) Provides MultiLine editing with vertical scroll bars.
Tasks:
User Interface and Properties
Form:
Name Property: Leave as is
Text Property: State of Ohio: RichTextBox and Buttons
BackColor Property: Web: Cornsilk
Font Property: Font: Times New Roman; Font style: Regular; Size: $14$; Script: Western
Toolbox | Property |
---|---|
RichTextBox |
Name: OhioRichTextBox Text: Nothing |
Button $1$ (RHS) |
Name: OhioButton Text: State of Ohio BackColor: Web: White |
Copy, Paste, Adjust, Align: Button $1$ Button $2$ (Middle position) |
Name: ClearButton Text: &Clear |
Copy, Paste, Adjust, Align: Button $1$ Button $3$ (RHS) |
Name: ExitButton Text: E&xit |
Select the three buttons.
Click the Format menu, Make Same Size: Both (as we did in the first flashcard)
(1.) Double click the State of Ohio button
(2.) Declare the variables
(3.) Write the code.
(4.) Code the Clear button and the Exit button
(5.) Build Solution
(6.) Run the program.
Please view the screenshots. Study the comments and the code.
We shall explore more toolbox controls in subsequent modules.
(1.) Using at least five complete sentences and at least five different variables and data types,
write a program of the summary of what you learned in this module.
(2.) Write a program of a short story, a poem, or drama using at least five sentences and at least five different variables and data types.
(3.) Write a program that displays examples of all the Value data types and the string data type.
(4.) Write a program that demonstrates at least ten examples of Implicit Type Conversions
Use the data types listed in this Module.
(5.) Write a program that demonstrates at least ten examples of Explicit Type Conversions
Use the data types listed in this Module.
(6.) Write a program of a short story, a poem, or drama using at least five sentences, the same variable,
and at least three different data types.
(7.) To be done by only one student on a first-come first-served basis
Assume you have three initials.
Write a program that declares variables to hold your three initials.
Display the three initials with a period following each one, for example: $S.D.C$
(1.) Provide any of these details if they are lacking in any DB post:
Well-written comments; another approach/method to solving the question; any additional relevant details; etc.
(2.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(3.) Other substantive responses.
(1.) Develop a Graphical User Interface (GUI) of a short story, a poem, or drama using at least five sentences and
at least five different variables and data types.
At least three buttons: the button that displays the information, the Clear button and the
Exit button should be included.
Include access keys for the three buttons.
(2.) Develop a Graphical User Interface of a short story, a poem, or drama using at least five sentences,
the same variable, and at least three different data types.
At least three buttons: the button that displays the information, the Clear button and the
Exit button should be included.
Include access keys for the three buttons.
(3.) Develop a GUI flashcard of all the Simple Types of the Value Types and the string data type.
A brief definition of each data type should be displayed when the user performs an event
(such as pointing the mouse or clicking) on each data type.
Use whatever toolbox controls you prefer.
number, variable, constant, literal, value element, operator, operand, operation, expression, arithmetic operators, assignment operators, comparison operators, conditional operator, tenary conditional operator, Boolean logical operators, bitwise and shift operators, equality operators, member access operators, member access expressions, type-testing operators, cast expression, user-defined conversion operators, pointer-related operators, null-forgiving operator, null-coalescing operator, lambda operator, scope resolution operator, namespace alias qualifier, await operator, delegate operator, New operator, Sizeof Operator, unary operators, binary operators, increment operator, decrement operator, plus operator, minus operator, multiplication operator, division operator, remainder operator, addition, operator, subtraction operator, prefix increment operator, postfix increment operator, prefix decrement operator, postfix decrement operator, compound assignment, operator precedence and associativity, arithmetic overflow, division by zero, round-off errors, floating-point division, operator overloading, access keys, TabIndex property, ComboBox, MessageBox, calculator, MaskedTextBox control, NumericUpDown control, KeyPress event, regular expressions (regex)
Students will:
(1.) Discuss the operators in C#
(2.) Perform operations on variables/values
(3.) Write C# programs involving the use of operators.
(1.) Textbook Chapter
(2.) C# Operators and Expressions: From: Overview To: Operator Overloading by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(3.) Type C# Numbers and/or C# Operators in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(4.) Type C# Numbers and/or C# Operators in the search bar and view/read the results.
These references will be useful as we progress through the course:
(5.) List of C# Math Functions
(https://docs.microsoft.com/en-us/dotnet/api/system.math?view=net-5.0)
(6.) Format Types in .NET
(https://docs.microsoft.com/en-us/dotnet/standard/base-types/formatting-types)
.NET means that the format types are applicable to C# and C#
(7.) Standard Numeric Format Strings
(https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings)
Operators are special symbols that perform specific operations on one or more operands,
and returns an output.
An Operand is the variable/value on which an operation is done.
An expression is a series of value elements combined with operators, which yields a new value.
Value elements include variables, constants, literals, properties, returns from Function, and Operator procedures, and
expressions.
The operators act on the value elements by performing calculations, comparison, or other operations.
The types of operators in C# are:
(1.) Arithmetic Operators
(2.) Assignment Operators
(3.) Comparison Operators
(4.) Conditional Operator
(5.) Boolean Logical Operators Please review Module 4 for the examples
(6.) Bitwise and Shift Operators
(7.) Equality Operators
(8.) Member Access Operators and Expressions
(9.) Type-testing Operators and Cast Expression
(10.) User-defined Conversion Operators
(11.) Pointer-related Operators
(12.) Null-forgiving Operator (!)
(13.) Null-coalescing Operator (??)
(14.) Lambda Operator (=>)
(15.) Scope Resolution Operator (::) (known in C# as Namespace alias qualifier)
(16.) Await Operator
(17.) Delegate Operator
(18.) New Operator
(19.) Sizeof Operator
Let us discuss some of these operators.
Arithmetic Operators are used to perform arithmetic operations with operands of numeric types.
They are grouped into Unary operators and Binary operators
The Unary operators are the:
(1.) Increment operator (++)
These consists of the Prefix Increment and the Postfix Increment operators
The prefix increment say: x++ is the value of x after the operation.
The postfix increment say: ++x is the value of x before the operation.
(2.) Decrement operator (--).
These consists of the Prefix Decrement and the Postfix Decrement operators
The prefix decrement say: x-- is the value of x after the operation.
The postfix decrement say: --x is the value of x before the operation.
(3.) Plus operator (+)
(4.) Minus operator (-)
The Binary operators are the:
(1.) Addition operator (+)
(2.) Subtraction (-) operator
(3.) Multiplication (*) operator
(4.) Division (/) operator
(5.) Remainder or Modulus operator (%): This is the integer remainder after a division.
Let us demonstrate some examples of Arithmetic operators.
Please review the screenshots and the comments.
Unary Arithmetic Operators
Student: Mr. C, how did you underline the words in the Console window?
The codes you used...
Teacher: Yes, the codes underline words in the Console window
They work for C# and C++ console window applications
You can also add foreground and background colors.
This is the List of the Console Log Formatting Commands
(https://www.samdomforpeace.com/References/ASCII.html#console)
\x1B[4m command underlines the text in the console.
\x1B[0m command resets it (closes the underlined text).
It is important to reset it, else it will underline the entire text in the console.
If you add foreground and background colors, it is also important to reset.
Notice that for C# (in that website), you can use the commands for (VB and C#) or you can use the commands for (C# and C++),
whichever you prefer. You can use both if you like.
Binary Arithmetic Operators
Teacher: Notice what we did for the division?
It is necessary for the result to be displayed as a double data type.
Let us solve more examples.
Please visit my website on Numbers
(www.numbersandnotations.appspot.com/numbers.html)
Let us solve Questions $10$, $6$, $7$, and $23$ on that website
We shall use only Arithmetic Operators to solve Question $10$
We shall cover Functions (Methods) in Module $6$. However, it is important to introduce you to C# Math Functions in
this module because we are dealing with Numbers in this module.
We shall use Arithmetic Operators and C# Math Functions to solve Questions 10, 6, 7, and 23
This is the List of C# Math Functions
(https://docs.microsoft.com/en-us/dotnet/api/system.math?view=net-5.0)
Please review the screenshots and the comments.
Teacher: You know one of the things I like about C#?
Student: What?
See how we declared the answers as double data type
But if the answer is an integer, C# displayed the answer as an integer rather than as a double
Java would have "messed" this up...displaying it as a double, then we have to convert that double back to an
integer
With C#, when we declare the answer as a double; if the answer is an integer, it will display it as an integer.
If the answer is a double, it will display it as a double.
Student: I like that too
Teacher: Yep...
But we need to declare it as a double because a double is a larger data type.
If we declare it as an integer and the answer is a double, then it will be rounded...that is not what we want.
Student: Look at Question (7.)
The answer on your website is not "exactly" the same as the answer displayed by the program
$84.7$ is not really $84.69999999999999$
Teacher: Good observation
The double data type has a double-precision floating point.
Hence, sometimes, it does not give the perfect accurate exact answer.
Assignment Operators are used to assign a value to a variable or property.
The equal sign is the assignment operator for programming languages (not just for C#)
Compound Assignment Operators are used to perform an operation on the value of a variable before assigning an
updated value to the variable.
They are:
$=$ operator (assignment operator)
$+=$ operator (compound assignment: add before assignment)
$-=$ operator (compound assignment: subtract before assignment)
$*=$ operator (compound assignment: multiply before assignment)
/= operator (compound assignment: divide before assignment)
\= operator (compound assignment: integer division before assignment)
^= operator (compound assignment: raise to an exponent before assignment)
≪ $=$ operator (compound assignment: arithmetic left shift before assignment)
≫ $=$ operator (compound assignment: arithmetic right shift before assignment)
&$=$ operator (compound assignment: concatenate a string expression to a string variable before assignment)
We use compound assignment operators if we want to do two things in one.
Rather than perform two tasks using two steps, perform those two tasks using one step.
Some people like it. Some people do not.
However, I prefer you learn it because you will most likely find it useful when we cover Statements in Module $5$
Let us demonstrate what I mean.
Please visit my website on Percent Applications
(www.fractions-decimals-percents.appspot.com/percentApplications.html)
Let us solve Question $1$ on that website
Because this calculation deals with currency (money), we shall use the currency format specifier
The advantage of using the currency format specifier is that it rounds the value to two decimal places
(money/currency is rounded to two decimal places) and it also includes the currency.
These are the Format Types in .NET
These are the Standard Numeric Format Strings
Let us format the result display in the console.
Please review the screenshots and the comments.
Student: Mr. C, I do not want to be confused by what you do.
Teacher: What is it my dear?
Student: You put the d in the first approach.
But you did not put the d in the second approach.
That is confusing...you do something for one and you do not do the same thing for another.
Teacher: I understand.
It is recommended that you put d when you declare a double data type for a variable.
However, by default; any decimal in C# is seen as a double data type.
That is also another reason to use the double data type rather than the float data type.
The first reason is because of the precision.
Another reason is that any decimal number in C# is a double data type by default.
So, if we forget to include the d after the decimal, that is not a problem.
It is better to include it.
But, it is not a problem if you forget to include it.
Student: Okay.
What if I write: const float serviceTip = 0.12
Will it work?
Teacher: No, it will not work because the decimal number is a double data type in C# by default.
If you want to use a float for that, you will need to include the f after the decimal number
Like const float serviceTip = 0.12f will work as a float.
However, keep in mind that the rest of the variables will have to be floats as well.
Otherwise you will have to convert them to floats.
It is much better to use the double data type.
Nice observation!
Comparison operators are operators that compare two operands and return a Boolean value.
The operands can be single values or expressions containing several values (enclosed in parentheses).
The operands can be numeric values, strings, and objects.
The Boolean value represents the relationaship of their values.
They are also known as Relational operators.
They include the:
$==$ (Equality) operator
$!=$ (Inequality or Not Equal) operator
< (Less than) operator
> (Greater than) operator
<= (Less than or equal to) operator
>= (Greater than or equal to) operator
Let us discuss Comparison operators.
Comparison Operator | Condition Tested | Examples |
---|---|---|
Comparing Numeric Values (Numbers) | ||
Equality: == | Is the value of the first expression equal to the value of the second expression? |
25 == 25 ' True 25 == 7 ' False |
Inequality (Unequal): != | Is the value of the first expression not equal to the value of the second expression? |
25 != 25 ' False 25 != 7 ' True |
Less than: < | Is the value of the first expression less than the value of the second expression? |
25 < 25 ' False 25 < 7 ' False |
Greater than: > | Is the value of the first expression greater than the value of the second expression? |
25 > 25 ' False 25 > 7 ' True |
Less than or equal to: <= | Is the value of the first expression less than or equal to the value of the second expression? |
25 <= 25 ' True 25 <= 7 ' False |
Greater than or equal to: >= | Is the value of the first expression greater than or equal to the value of the second expression? |
25 >= 25 ' True 25 >= 7 ' True |
Comparing Strings | ||
Equality: == |
Default sorting: Ascending order (from least to greatest) Is the first character in the first string sorted as the first character in the second string? If yes, is the second character in the first string sorted as the second character in the second string? If yes, is the third character in the first string sorted as the third characer in the second string? ...and so on |
"25" == "25" ' True because 2 = 2; 5 = 5 "255" == "25" ' False because "255" is a longer string "555" == "55" ' False because "555" is a longer string "251" == "253" ' False because 2 = 2; 5 = 5; but 1 is not equal to 3 "25" == "7" ' False because 2 is not equal to 7 |
Inequality (Unequal): != |
Default sorting: Ascending order (from least to greatest) Is the first character in the first string not sorted as the first character in the second string? If yes, is the second character in the first string not sorted as the second character in the second string? If yes, is the third character in the first string not sorted as the third characer in the second string? ...and so on |
"25" != "25" ' False because 2 is not unequal to 2; 5 is not unequal to 5 "251" != "253" 'True because 2 is not unequal to 2; 5 is not unequal to 5 but 1 is not equal to 3 "253" != "789" ' True because 2 is not equal to 7 |
Less than: < |
Default sorting: Ascending order (from least to greatest) Is the first character in the first string sorted before the first character in the second string? If yes, is the second character in the first string sorted before the second character in the second string? If yes, is the third character in the first string not sorted as the third characer in the second string? ...and so on |
"25" < "25" ' False because 2 is not less than 2 "25" < "7" ' True because 2 is less than 7 "25" < "154" ' False because 2 is greater than 1 |
Greater than: > |
Default sorting: Ascending order (from least to greatest) Is the first character in the first string sorted after the first character in the second string? If yes, is the second character in the first string sorted after the second character in the second string? If yes, is the third character in the first string not sorted as the third characer in the second string? ...and so on |
"25" > "25" ' False because 2 is not greater than 2 "25" > "7" ' False because 2 is less than 7 "25" > "154" ' True because 2 is greater than 1 |
Less than or equal to: <= |
Default sorting: Ascending order (from least to greatest) Is the first character in the first string sorted before, or sorted as the first character in the second string? If yes, is the second character in the first string sorted before, or sorted as the second character in the second string? If yes, is the third character in the first string not sorted as the third characer in the second string? ...and so on |
"25" <= "25" ' True because 2 is equal to 2, and 5 is equal to 5 "25" <= "7" ' True because 2 is less than 7 "25" <= "154" ' True because 2 is greater than 1 |
Greater than or equal to: >= |
Default sorting: Ascending order (from least to greatest) Is the first character in the first string sorted after, or sorted as the first character in the second string? If yes, is the second character in the first string sorted after, or sorted as the second character in the second string? If yes, is the third character in the first string not sorted as the third characer in the second string? ...and so on |
"25" >= "25" ' True because 2 is equal to 2, and 5 is equal to 5 "25" >= "7" ' False because 2 is less than 7 "25" >= "154" ' True because 2 is greater than 1 |
For the rest of the String comparisons, please review Module 4 For comparing objects, please review the Advanced Visual Basic course. |
One of the nice features of the C#langauge is the Input/Output feature.
This feature is interactive.
You use this input/output feature in several applications.
A common application is an application that verifies one's identity by inputting the first name, last name, date of
birth, etc.
To use the Input/Output feature, the Console.ReadLine() method is used.
Remember we discussed the Console.ReadLine() and the Console.ReadKey() methods in Module $1$. Please review Module $1$
Console.ReadLine() method reads the next line of characters from the standard input stream.
It reads strings.
Console.ReadKey() method: obtains the next character or function key pressed by the user.
We also have:
Console.Read() method: This method reads the next character from the standard input stream.
We shall cover Functions in Module $5$. For now, let us just stick with the Console.ReadLine() method.
Let us demonstrate the input/output feature with numbers so we see how it works.
Please review the screenshots and the comments.
Input/Output Feature: Example $1$
Let us solve Question $12$ on the Numbers
website.
Input/Output Feature: Example 2
Let us do a real-world application for this example.
Onto the ...
Please review the BMI information on these two government websites [from the Center for Disease Control and Prevention (CDC) and the National Heart, Lung, and Blood Institute of the National Institutes of Health (NIH)]
About Adult BMI | Healthy Weight, Nutrition, and Physical Activity | CDC and
Calculate Your BMI - Standard BMI Calculator
As at today, the 3rd day of September, 2020; the BMI information on both websites are:
NIH website
Calculate Your BMI - Standard BMI Calculator
CDC website
About Adult BMI | Healthy Weight, Nutrition, and Physical Activity | CDC
$ BMI = \left(\dfrac{weight}{height * height}\right) * 703 \\[5ex] weight\:\:is\:\:in\:\:pounds (lb) \\[3ex] height\:\:is\:\:in\:\:inches (in) $
$ BMI = \left(\dfrac{weight}{height * height}\right) \\[5ex] weight\:\:is\:\:in\:\:kilograms (kg) \\[3ex] height\:\:is\:\:in\:\:meters (m) \\[3ex] $ If you need help with conversion of units, please review the Tables and Examples in Measurements and Units
Teacher: What do you notice in both websites?
Student: They both have the information on the BMI.
In addition, the CDC website has information for both Adult BMI and Child & Teen BMI among others.
The NIH website has recommendations among others.
Teacher: That is correct. What else?
Student: They have the BMI calculator.
Teacher: Did you notice any difference in the calculator on both websites?
Student: The NIH website has BMI calculator for both Standard and Metric versions.
The CDC website has the BMI calculator for only the Metric version.
Teacher: Did you notice any issue/concern about the BMI information?
Student: Not really. Why?
Teacher: So, this is what we are going to do.
Let us develop the BMI calculator.
That calculator will calculate the BMI.
Then, we shall interpret that BMI, and make a recommendation.
.
The CDC website gave us the formula for calculating the BMI. So, we shall use it.
As you can see, our calculator would have to use conditional statements for the interpretation and recommendation.
But, here is the issue.
Student: Wait, I think I see the issue.
The issue is with the domains.
Teacher: Correct!
Anyone having a BMI between $18.5$ and $24.9$ both endpoints included has a Normal weight.
This is: Normal weight: [18.5, 24.9]. It is a closed interval (relate with Mathematics).
So, the Overweight range for the BMI should be the weight greater than $24.9$, (rather than beginning from $25$) and ending at $29.9$
For the Overweight range, the first endpoint is not included, but the second endpoint is included.
This is: Overweight: (24.9, 29.9]. It is a half-open half-closed interval (relate with Mathematics)
Teacher: Do you know why this would be a problem if the programmer does not fix these issues before developing the calculator?
Student: Yes. Because there would not be any interpretation for anyone whose BMI is between $24.9$ and $25$
But, I do see that the BMI information is for values rounded to one decimal place.
Teacher: That is correct.
And we shall develop our calculator to round to one decimal place.
But, it is important we fix the issues.
What if we do not want to round?
Look at the two examples on the CDC website. The BMI values were rounded to two decimal places.
If we developed our calculator to round to two decimal places with the information on those websites "as is"; then we would not have the interpretation and recommendation for those two examples ($24.98$ and $24.96$) because those values are greater than $24.9$ but less than $25$.
Student: That makes sense.
So, the last one: Obese should be BMI greater than $29.9$, rather than greater than $30$?
Teacher: That is correct.
Let us apply what we learned so far.
We shall develop a console application and a desktop application for the Body Mass Index (BMI) calculator.
I do the console application.
You do the desktop application.
We are yet to cover Statements (covered in Module 5). However, do not worry.
I explained my comments very well. You will understand the comments.
Please ask questions if you do not understand any of the comments.
We shall use part of Module $5$ (Decision-making statements) in the program.
Please review the screenshots and the comments.
(1.) The program should accept user inputs of:
(I.) First name
(II.) Last name
(III.) Weight
(IV. Height
(2.) The program should output the:
(A.) BMI value
(B.) Interpretation
(C.) Recommendation
(3.) The program should address user-input errors of non-positive numbers for the weight and the height.
Inform the user.
Then, exit the program. Do not allow the program to continue.
To exit the program, we use the command: Environment.Exit(0); or Application.Exit();
Conditional Logical AND in C# is represented by the double ampersand symbol &&
Conditional Logical OR in C# is represented by the double pipe symbol ||
Student: I have several questions, Mr. C
Teacher: Please go ahead
Student: First Question: Why did you initialize those variables?
The interpretBMI and the adviceBMI...you initialized them to String.Empty
Teacher: Good question.
Assume we did not initialize them
We only defined them within the block of code: the If Statement
Then, we want to print them/output them outside the block of code
The program "will not be happy"
Compare it to this scenario.
A student registered to attend a school.
We did not register the student at the front office registration desk.
But we sent the student to a classroom and the classroom teacher registered that student.
The parents come, looking for their child.
Where will the parent go first?
Student: At the front desk of course
Teacher: Good.
The front desk will first keep a record of the student before sending the student to the class.
We have to first assign the string to something before we send it to the blocks of code, and then output it.
We cannot just declare it without an assignment, then send it to a block of code to be used within that block of
code only, and then want to output it outside the block of code.
Does it make sense?
Student: Yes, it does.
But what if we do not want to print the value outside the block of code?
What if we want to print the value inside each block of code where it is used?
Teacher: I am impressed by your questions.
Yes, we can do that.
But you know what that means...right?
Student: We have to write it each time for each of the conditional statement.
Teacher: That is correct.
Student: Second Question: Why did you underline the 0 on the console window?
....process exited with 0?
Teacher: Unless defined in the program otherwise; anytime you run a program and the program exited with 0,
it means that the program successfully exited.
0 basically lets you know that the program ended successfully.
A very important concept of software design is to plan for user-input errors.
Every user is not expected to know how to use your software.
Have you read/seen events where a child gets the parents iPad and purchases applications (apps) without their
consent/approval; and funny enough, when the child does not even that he/she purchased those apps?
Maybe the parents should enable some authentication factors before apps are purchased.
Maybe Apple should not store the debit/credit card information on the device.
Well, considering the fact that the two main goals of every business (including non-profit organizations) is to:
Maximize profit and Minimize cost; the second "Maybe" is unlikely.
Be it as it may; we want to address user-input errors in any software we design: console application, desktop application,
web application, and mobile application.
For example: for the Midterm Project in Module 5; say you did an application that involves the user to enter in the Tax
percentage, we know the tax cannot be negative.
So, you can prevent the user from entering a negative number (preventing an error in the final result) or you can notify the
user that a negative number is not allowed.
Addressing user-input errors includes:
(1.) Prevent errors: Prevent the user from making an error.
For example: If you want the user to enter only positive integers in a specific TextBox, design the software
in such a way that the TextBox will not accept nonpositive integers (zero and negative integers).
(2.) Handle errors: also known as Error Handling or Exception Handling
Handle any error made by the user.
The Visual Studio IDE throws an exception (error) in some cases. We shall discuss these kinds of exceptions in the Advanced C#
course.
However, it is important to handle those errors overlooked by Visual Studio.
An example is the code we wrote in Lines #73 - #77 and Lines #80 - #84 (though we wrote it for console application)
We can write similar code for desktop applications.
Let us discuss some approaches to preventing errors when working with numeric data types.
They are:
(1.) MaskedTextBox control
(2.) NumericUpDown control
(3.) TextBox control using KeyPress event with Regular Expressions
The MaskedTextBox
uses a mask to distinguish between proper and improper user input.
A Mask
is the default property for the MaskedTextBox
It is a string (because TextBoxes accept only strings) composed of one or more masking elements.
(Please see the table for the masking elements)
As you notice from the last screenshot, there are System predefined masks for phone numbers, social security number, date,
time, and zip code.
However, we can select our define our own mask (custom mask).
The System predefined masks are the ones I recommend.
I do not recommend the use of custom masks unless your professor says otherwise.
Nevertheless, let us discuss it, should you find them useful for your personal projects.
We define custom masks based on these descriptions.
Masking Element | Description |
---|---|
$0$ |
Required: Any digit between $0$ and $9$ is accepted This means only nonnegative integers Say we want the MaskedTextBox to require only two nonnegative integers, we define the custom mask as $00$ |
$9$ |
Optional: Digit or Space Say we want the MaskedTextBox to allow two nonnegative integers, we define the custom mask as $99$ |
# |
Optional: Digit, Space, and Plus/Minus signs This means all integers (including positive, zero, and negative integers) Say we want the MaskedTextBox to allow a negative two-digit integer, say $-37$ we define the custom mask as ### The first # is for the minus (negative) sign The other two ## are for the integers |
$.$ |
Optional: Decimal placeholder Say we want the MaskedTextBox to require one digit to one decimal place, say $7.3$; we define the custom mask as #.# or 0.0 or 9.9 Say we want the MaskedTextBox to require two digits to two decimal place, say $12.34$; we define the custom mask as ##.## or 00.00 or 99.99 Say we want the MaskedTextBox to require the negative value of two digits to two decimal place, say $-52.79$; we define the custom mask as ###.## |
$,$ |
Optional: Thousands placeholder For displaying the thousandth unit or breaking a long digit in thousands. |
$\$$ |
Optional: Dollar currency symbol For displaying the dollar currency. |
/ | Date separator |
: | Time separator |
$L$ |
Required: Letter (lowercase and uppercase English Language alphabet) Say we want the MaskedTextBox to require three letters, we define the custom mask as $LLL$ |
$?$ |
Optional: Letter (lowercase and uppercase English Language alphabet) Say we want the MaskedTextBox to allow three letters, we define the custom mask as $???$ |
& |
Required: Character (non-control characters including alphabets of all Languages and digits) Say we want the MaskedTextBox to require three characters, we define the custom mask as &&& |
$C$ |
Optional: Character (non-control characters including alphabets of all Languages and digits) Say we want the MaskedTextBox to allow three characters, we define the custom mask as $CCC$ |
$A$ | Required: Alphanumeric character |
$a$ | Optional: Alphanumeric character |
< |
Shift down. It converts all the characters that follow behind it to lowercase. |
> |
Shift up. It converts all the characters that follow behind it to uppercase. |
| | Disable a previous shift down or shift up. |
\ |
Escape sequence. It masks a character, turning it into a literal. |
Let us review some examples of the MaskedTextBox for Numbers.
Form1.cs: Adjust and Align
(Name) property: Leave as is. Do not change
Text property: Numbers Validation: MaskedTextBox
BackColor property: Web: Biege
Font: property: Font: Times New Roman; Font Style: Regular; Size: 18
FormBorderStyle property: Fixed3D
MaximizeBox property: False
Toolbox Controls | Property |
---|---|
Label: Adjust and Align | Text: Age (years): |
MaskedTextBox: Adjust and Align | (Name): YearsMaskedTextBox |
Label: Adjust and Align | Text: Nonnegative Integers only |
Teacher: Let us set the property for the MaskedTextBox Have you seen anyone that is more than $3-digits$ in age? Student: No, Mr. C The oldest man that ever lived is Methuselah. He was 969 years old. And that is three digits. Teacher: Okay, let us set the MaskedTextBox for Age. Let us set it to three digits. However, we will make it optional. This means that we shall use $999$ rather than $000$ Student: So, the user cannot enter any negative number in that MaskedTextBox? Teacher: That is correct. It prevents the user from entering a negative number or from entering a string. Only a one-digit, tw0-digit, or three-digit nonnegative integer is allowed. Let us review more examples. |
|
Label: Adjust and Align |
Text: Account (in red): ForeColor: Web: Red |
MaskedTextBox: Adjust and Align |
(Name): RedAccountMaskedTextBox Mask: ####.## (for $-120.55$) |
Label: Adjust and Align | Text: $\$$ |
Label: Adjust and Align | Text: Negative Decimals |
Label: Adjust and Align |
Text: Account (in green): ForeColor: Web: Green |
MaskedTextBox: Adjust and Align |
(Name): GreenAccountMaskedTextBox Mask: ###.## (for $120.75$) |
Label: Adjust and Align | Text: $\$$ |
Label: Adjust and Align | Text: Nonnegative Decimals |
Button: Adjust and Align |
Name: DemoButton Text: Demonstrate BackColor: Web: White |
We use the MaskedTextBox just as we use the TextBox (it is a TextBox anyway, just that it is masked).
All the user-input in a TextBox (including the MaskedTextBox) are treated as strings.
So, we will need to convert it to a numeric data type, use the numbers, and then reconvert back to string
using String Interpolation or the ToString() method in order to display it in a Label or MessageBox.
We have used labels in previous applications.
Let us use a MessageBox this time.
Let us demonstrate the MaskedTextBox with a Button and a MessageBox.
A MessageBox displays a message box.
The MessageBox accepts only strings. Hence, we need to use the String Interpolation (my preference) to display those
values as strings.
A frequently-used method of the MessageBox is the
MessageBox.Show() method.
(https://docs.microsoft.com/en-us/dotnet/api/system.windows.messagebox.show?view=net-5.0)
The NumericUpDown control displays a single numeric value that the user can increment
(by clicking the Up arrow key on the control) or decrement (by clicking the Down arrow key on the control)
Alternatively, the user can type a number in the box part of the control.
The control displays and sets a single numeric value from a list of fixed numeric-value choices.
It is a good choice for creating a volume control for a music player application.
Let us review some examples of the NumericUpDown for Numbers.
Form1.cs: Adjust and Align
(Name) property: Leave as is. Do not change
Text property: Numbers Validation: NumericUpDown
BackColor property: Web: SeaShell
Font: property: Font: Times New Roman; Font Style: Regular; Size: 18
FormBorderStyle property: Fixed3D
MaximizeBox property: False
Toolbox Controls | Property |
---|---|
Label: Adjust and Align | Text: Age (years): |
NumericUpDown: Adjust and Align | (Name): YearsNumericUpDown |
Label: Adjust and Align | Text: Nonnegative Integers only |
Teacher: Let us set the property for the YearsNumericUpDown Rather than use 999 that we used in the MaskedTextBox, let us: Leave DecimalPlaces property: 0 "as is" Set: Increment property: 1 "as is" because the age of someone increases by 1 Set: Maximum property: 999 Set: Minimum property: 0 because someone can be 0 years and some months |
|
Label: Adjust and Align | Text: Age (months): |
NumericUpDown: Adjust and Align |
(Name): MonthsNumericUpDown DecimalPlaces: 0 Increment: 1 Maximum: $999 * 12 = 11988$ Minimum: 1 (because someone's age cannot be zero months) |
Label: Adjust and Align | Text: Positive Integers only |
Label: Adjust and Align |
Text: Account (in red): ForeColor: Web: Red |
NumericUpDown: Adjust and Align |
(Name): RedAccountNumericUpDown DecimalPlaces: $2$ Increment: $0.01$ Maximum: $-0.01$ Minimum: $-1000000000.00$ |
Label: Adjust and Align | Text: $\$$ |
Label: Adjust and Align | Text: Negative Decimals only |
Label: Adjust and Align |
Text: Account (in green): ForeColor: Web: Green |
NumericUpDown: Adjust and Align |
(Name): GreenAccountNumericUpDown DecimalPlaces: $2$ Increment: $0.01$ Maximum: $1000000000.00$ Minimum: $0.01$ |
Label: Adjust and Align | Text: $\$$ |
Label: Adjust and Align | Text: Nonnegative Decimals only |
Button: Adjust and Align |
Name: DemoButton Text: Demonstrate BackColor: Web: White |
The NumericUpDown control accepts numeric data types (decimal, floating point types, and integral types)
However, it displays only the decimal by default (because of the DecimalPlaces property which must have a value)
This implies that in order to display any data type that is not a decimal, a conversion is required.
For example: to display a value as an integer, an explicit conversion (casting) is required because the decimal type is the
larger data type. (decimal is larger than an integer)
To display a value as a double, an implicit conversion is required because the decimal type is smaller data type
(decimal is smaller than a double)
If you do not want to convert, then you have to declare the variable as a decimal type.
Let us implement a NumericUpDown control
Teacher: Do you understand what I did in Lines #38 and #40?
I wanted to "mess things up" a little bit. I hope it did not confuse you.
I used a String Interpolation. However, I did not want to use the currency format specifier to display the currencies
like I did for the MaskedTextBox
Line #38: Will display the dollar symbol though I did not use the currency format specifier
Line #40: Had to convert the decimal to double before adding it to the other double and then used the currency
format specifier to express the balance.
We shall discuss these approaches with the String data types in Module $4$
Teacher: Would you rather prevent errors or handle errors?
Student: I would prevent them.
It's better that way.
Teacher: True. But some errors may not be preventable.
Hence, we still need to know how to handle them.
Student: Can you give an example of a non-peventatble error?
Teacher: I'm just saying (speaking like an American lol)
For example: let's say in the Midterm Project (which is a Piecewise Function application)
Let's say you were doing an application on Power Rates
A user may input a final reading that is less than the initial reading
And the user may input it intentionally or unintentionally
Student: But can we not find a way to use any of these approaches and prevent it?
Teacher: We can.
Let us make a note of an important concept: Property Names of the Toolbox Controls
Notice the three dots in this screenshot image (indicated by the arrow):
Whenever you notice something like that anywhere in your code, it is important to point your mouse at it and click the
Show potential fixes link:
Notice the issue was a naming rule violation. It is not a "big" issue hence those three dots.
It is not a warning. It is not an error. But it is a violation.
You do want to ensure your project is free of all violations (not just warnings and errors).
So, let us address that naming rule violation.
Going forward, we shall name each property of any toolbox control using Pascal casing.
Let us apply the knowledge we acquired in this module to develop a desktop application.
Which application comes to mind right away...a desktop application that deals with Numbers and Operators?
It's the Standard Calculator. Let's develop it. 😊
Please review the desktop applications we developed in previous modules beginning from Module $1$
Let us begin with the desktop calculator on your Windows PC/Laptop
Please see the screenshots
Let us develop the function buttons as seen in the red rectangle.
We are yet to cover Statements (covered in Module $5$). However, do not worry.
I explained the comments very well. You will understand the comments.
Please ask questions if you do not understand any of the comments.
We shall use part of Module $5$ (Conditional statements) in the program.
Form1.cs: Adjust and Align
(Name) property: Leave as is. Do not change
Text property: Standard Calculator © 2021 SamDom4Peace Designs (Sample)
BackColor property: Web: SeaShell
Font: property: Font: Times New Roman; Font Style: Regular; Size: 18
FormBorderStyle property: Fixed3D
MaximizeBox property: False
The MaximizeBox property is set to False if we do not want the user to maximize the application.
The reason is because we want the interface to have a consistent look.
Toolbox Controls | Property |
---|---|
Label: Adjust and Align |
AutoSize: False (do this first) BorderStyle: Fixed3D Text: Delete label1 Adjust and Align again TextAlign: MiddleRight (Name): CalculatorLabel |
TextBox: Adjust and Align |
Text: $0$ (because we want $0$ to be the default) TextAlign: Right (because we want to align the $0$ to the right) (Name): CalculatorTextBox |
Button: Adjust and Align |
Text: $1/x$ BackColor: Web: White (Name): ReciprocalButton |
Copy and Paste Button: Adjust and Align |
Text: $x^2$ (Name): SquareButton |
Copy and Paste Button: Adjust and Align |
Text: $\sqrt{x}$ (Name): SquareRootButton |
Copy and Paste Button: Adjust and Align |
Text: $\div$ (Name): DivideButton |
Copy and Paste all previous four Buttons: Adjust and Align Then, begin to work on each button. |
Text: $7$ (Name): SevenButton |
Button: Adjust and Align |
Text: $8$ (Name): EightButton |
Button: Adjust and Align |
Text: $9$ (Name): NineButton |
Button: Adjust and Align |
Text: $\times$ (Name): MultiplyButton |
Copy and Paste all previous four Buttons: Adjust and Align Then, begin to work on each button. |
Text: $4$ (Name): FourButton |
Button: Adjust and Align |
Text: $5$ (Name): FiveButton |
Button: Adjust and Align |
Text: $6$ (Name): SixButton |
Button: Adjust and Align |
Text: $-$ (Name): MinusButton |
Copy and Paste all previous four Buttons: Adjust and Align Then, begin to work on each button. |
Text: $1$ (Name): OneButton |
Button: Adjust and Align |
Text: $2$ (Name): TwoButton |
Button: Adjust and Align |
Text: $3$ (Name): ThreeButton |
Button: Adjust and Align |
Text: $+$ (Name): PlusButton |
Copy and Paste all previous four Buttons: Adjust and Align Then, begin to work on each button. |
Text: $+/-$ (Name): PlusMinusButton |
Button: Adjust and Align |
Text: $0$ (Name): ZeroButton |
Button: Adjust and Align |
Text: $.$ (Name): DecimalButton |
Button: Adjust and Align |
Text: $=$ (Name): EqualButton |
Copy and Paste Button: Adjust and Align |
Text: &Clear (Access key: C) (Name): ClearButton |
Copy and Paste Button: Adjust and Align |
Text: E&xit (Access key: x) (Name): ExitButton |
(1.) Double-click the $1/x$ button in the Design window.
This leads to the Code window
Scroll a little bit to the top, write the comments, and begin to...
(2.) Write the code.
Let us use a top-down approach.
Double-click each button in the Design window to open the Code window.
Then write the code for the event: what should happen when the user clicks the button?
Please review the screenshots.
Review the comments.
Design Area
Access keys: C for the Clear and x for the Exit buttons
Program Code
Run the Program
$\infty$ means Infinity
NaN means Not a Number
It is not a real number.
But it is an imaginary number.
It is covered under Complex Numbers in Algebra)
This calculator deals with only with real numbers.
$-\infty$ means Negative Infinity
Functionalities of the Calculator
(1.) For operation involving two numbers: the calculator works for any positive numbers
(2.) For operation involving two numbers: the calculator works if the first number is negative
(3.) For operation involving one number: the calculator works for any number
(4.) For any operation: the user sees what he/she did
(5.) Division of a number by zero and the square root of a negative number is handled.
Limitations of the Calculator
(1.) For operation involving two numbers: the calculator does not work for two negative numbers
(2.) The calculator computes one operation at a time. It does not do multiple operations simultaneously
Let us design another calcuator using more toolbox controls.
For this calculator:
(1.) We want two TextBoxes for user-input.
The two TextBoxes will receive user-input for two numbers (the operands).
Remember that TextBoxes accept only strings.
But we want them to accept numbers.
We shall define those numbers using the double data type (to accomodate decimals).
Then, we shall convert those numbers as strings so that the TextBoxes will accept them.
(2.) We want a ComboBox.
The ComboBox will contain a dropdown list of items: the operations.
We shall expand our list of operations. So, this calculator will be more of a scientific calculator.
I shall do some functions.
You do the rest of the functions (just as we did for the Standard Calculator).
We shall use an access key with the ComboBox.
(3.) We want four buttons: the Calculate, Clear Some, Clear All, and Exit buttons.
We shall use access keys with these buttons.
(4.) When we run our program, we want the cursor to be focused on the first TextBox.
Then, we want the user to be able to use the Tab key on the keyboard to perform any operation without using a mouse.
This is an important software design concept to accommodate users with disabilities.
Access keys is one of the ways to work only with the keyboard keys.
Another way is the TabIndex Property.
Once the user enters the first number in the first TextBox; move to the ComboBox and select an operation from the
dropdown list and press the Tab key; use the Tab to move to the second TextBox (as applicable), enter the second number and
press the Tab key (as applicable); move to the Calculate button and hit the Enter key to get the result.
The TabIndex property controls that ability for the Tab to move in that order.
We shall set the TabIndex property of the toolbox controls accordingly.
For operations that involve two numbers such as calculating the sum, difference and the like: we want it to be:
first number → operation → second number → calculate
For operations that involve only one number such as calculating the reciprocal, square root and the like: we want to
disable the second TextBox so that the user would not enter a second number.
The TabIndex property contains a number that represents that order in which the toolbox controls are added to the form.
It determines the order in each toolbox control receives focus when the user presses the Tab key or uses an Access key
while an application is running.
The TabIndex property is zero-indexed. This means that the first one begins with a 0, the next one is a 1, the next is a 2
among others.
The TabIndex can be changed by:
(1.) Click the form: → View menu → the Tab Order or
(2.) Click each control and change the TabIndex property from the Properties menu.
It is important to note that some toolbox controls do not have a TabIndex property.
Form1.cs: Adjust and Align
(Name) property: Leave as is. Do not change
Text property: Scientific Calculator © 2021 SamDom4Peace Designs (Sample)
BackColor property: Web: Olive
ForeColor property: Web: White
Font: property: Font: Times New Roman; Font Style: Regular; Size: 18
FormBorderStyle property: Fixed3D
MaximizeBox property: False
We set the MaximizeBox property to False because we do not want the user to maximize the application.
We want the interface to have a consistent look.
Toolbox Controls | Property |
---|---|
Label: Adjust and Align |
Text: First Number: |
TextBox: Adjust and Align |
Text: TextAlign: Right (because we want to align the number to the right) (Name): FirstNumberTextBox |
Copy the previous label: Adjust and Align Label: |
Text: Operation: |
ComboBox: Adjust and Align Please see the screenshots on how to insert the ComboBox |
Text: (Name): OperationComboBox |
The items in the ComboBox are written that way for teaching purposes.
Reviewing those items, it is easy for you to see the operations that involve one number (first number only) and the
operations that involve two numbers (the first number and the second number)
Select the first label (click) and TextBox (CTRL) Copy (CTRL + C) and Paste (CTRL + V) Label: Adjust and Align |
Text: Second Number: |
Select the first label (click) and TextBox (CTRL) Copy (CTRL + C) and Paste (CTRL + V) TextBox: Adjust and Align |
(Name): SecondNumberTextBox |
Select the first label (click) and TextBox (CTRL) Copy (CTRL + C) and Paste (CTRL + V) Label: Adjust and Align |
Text: Result: |
Label: Adjust and Align |
AutoSize: False (do this first) Text: Delete label5 (Name): ResultLabel BackColor: Web: White BorderStyle: Fixed3D ForeColor: Web: Black |
Button: Adjust and Align |
Text: Clear &All (Access key: A) (Name): ClearAllButton BackColor: Web: White ForeColor: Web: Black |
Copy and Paste Button: Adjust and Align |
Text: Clear &Some (Access key: S) (Name): ClearSomeButton |
Copy and Paste Button: Adjust and Align |
Text: &Calculate (Access key: C) (Name): CalculateButton |
Copy and Paste Button: Adjust and Align |
Text: E&xit (Access key: x) (Name): ExitButton |
Select the four buttons and Format: Make Same Size: Both |
Let us make sure the Tab controls are set in order based on the TabIndex Property
The user may decide to use the access key to do the calculation.
However, we want the user to be able to use only the Tab key and perform operations because the some users may not
remember access keys. Besides, any two programmers may decide to use different access keys for the same button.
If the user does ALT + C, it leads to the Calculate button and the calculation is done.
Alternatively, the user can decide to move the Tab key to the Calculate button and then press the ENTER key when the focus
is on the button. The calculation will also be done.
Either way is fine. However, the use of only the Tab key has the priority.
It is necessary to accommodate users by allowing users to perform operations with Tab keys especially when they
do not know the access keys.
Hence, the TabIndex property is important.
Because we would like the tab to move to the Clear All button before the Exit button, let us change the TabIndex properties
of the Clear All button and the Exit button.
Click the View → Tab Order again to remove the tab positions.
Click the Clear All button and change the TabIndex property from $11$ to $10$
Click the Exit button and change the TabIndex property from $10$ to $11$
Verify by viewing the tab order again.
Recap:
Assume the user is working with only the keyboard (software design to accommodate users who cannot use the mouse)
(1.) When the user runs the application, the cursor focus should be in the first TextBox waiting for user input.
The user enters a number and presses the tab key
(2.) The next focus should be the ComboBox waiting for the user to make a selection.
The user selects an operation.
If the operation involves only one number, the second TextBox is disabled so the focus moves to the Calculate
button.
The command used to disable the TextBox is: TextBox.Enabled = false;
As you can see, to disable a TextBox; the Enabled property of the Textbox is set to the Boolean value: false
If the operation involves two numbers, the cursor focus moves to the second TextBox waiting for the user to enter the
second number. The user enters the second number and presses the tab key.
The next focus would be the Calculate button.
The user presses the ENTER key and the calculation is done. The result is displayed in the label: ResultLabel.
(3.) The user presses the tab key and the focus should be the Clear Some button.
The user presses the ENTER key and the entries in the TextBoxes and the label are cleared.
(4.) The user presses the tab key and the focus should be the Clear All button.
The user presses the ENTER key and all entries (all items in the ComboBox) are cleared.
(5.) The user presses the tab key and the focus is the EXit button.
The user presses the ENTER key and the application is closed.
A ComboBox
is a combination of a TextBox and a ListBox.
(https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.combobox?view=net-5.0)
It enables the user to select items from the a list or enter a new value.
It is an object of the ComboBox class.
There are several properties of the ComboBox.
We shall discuss only one property in this module: the SelectedIndex
property.
The SelectedIndex property gets or sets the index of a selected item.
The ComboBox items are zero-indexed just like arrays.
This means that the first item has index: $0$, the second item has index $1$, and the third item has index $2$ among others.
The command used to specify a selected item in the ComboBox is: ComboBox.SelectedIndex == Index
Based on the items in the ComboBox in our program:
ComboBox Items | Index |
---|---|
Addition (+) [2 numbers] | $0$ |
Subtraction (-) [2 numbers] | $1$ |
Multiplication (*) [2 numbers] | $2$ |
Division (÷) [2 numbers] | $3$ |
Modulo (mod) [2 numbers] | $4$ |
Exponent (xⁿ) [2 numbers: x is the base; n is the exponent] | $5$ |
$Log_{x}n$ [2 numbers: x is the base; n is the number] | $6$ |
nth Root of x [2 numbers: x is the radicand; n is the index] | $7$ |
Reciprocal (1/x) [1 number] | $8$ |
Percent (%) [1 number] | $9$ |
Absolute Value (|x|) [1 number] | $10$ |
n! [1 number] | $11$ |
Tangent in DEG (tan) [1 number] | $12$ |
Sine in RAD (sin) [1 number] | $13$ |
Cosine in GRAD (cos) [1 number] | $14$ |
(1.) Double-click the Calculate button in the Design window.
This leads to the Code window
Scroll a little bit to the top, write the comments, and begin to...
(2.) Write the code.
What should happen when the user clicks the Calculate button?
Please review the screenshots.
Review the comments.
Design Area
Access keys: C for the Calculate, A for the Clear All, S for the Clear Some and
x for the Exit buttons
Program Code
Another approach to clearing texts in the Textbox is to use the Clear() method. For example: Textbox.Clear();
To clear all the items in a ComboBox besides the selected item, we also use the Clear() method.
For example: ComboBox.Items.Clear();
To clear the selected item in a ComboBox, we use the command: ComboBox.ResetText();
Student: Mr. C, you used the same name variable: result for different events.
Is that allowed?
Teacher: Very good observation.
Yes, we can do that.
Here is the reason: we used it within each event (each conditional statement).
We defined it as a class member variable. But remember we did not specify any value for it.
Hence, we are free to use it as local variables.
But you are very welcome to use different variables for the different events if you choose.
Notice that we did not have issues with the variables we defined in the class such as firstNumber
We can use those variables anywhere within the class.
Student: Another question.
You did not convert the variable: result back to a string. It is a double...right?
I thought we were supposed to convert it back to a string to display it in the label because the label accepts only
strings just like the TextBox. Is that correct?
Teacher: That is correct.
We are supposed to convert it back to a string in order to display it in the label.
However, the String Interpolation takes care of that.
That is one of the several benefits of using String Interpolation in the formatting of the output.
Notice I have been using it since we discussed it in Module 1
Student: I guess those whitespaces are to format the display of the result?
Teacher: That is correct.
Run the Program
(1.) Visit my website on Numbers
(www.numbersandnotations.appspot.com/numbers.html)
Choose any applicable question and write a C# program to solve it.
Please make sure that the output of your program gives the same result as the solution of the
question on my website.
You may use Arithmetic Operators, Math Functions, or both.
(2.) Visit my website on Percent Applications
(www.fractions-decimals-percents.appspot.com/percentApplications.html)
Choose any applicable question and write a C# program to solve it.
Please make sure that the output of your program gives the same result as the solution of the
question on my website.
You may use Arithmetic Operators, Math Functions, or both.
(3.) Program to determine your age
***Because your age is a PII (Personal Identifiable Information), you may use a fictitious age.
However, you need to test it (privately) with your actual age to make sure it works.***
Develop a C# program to determine your age based on these instructions.
ONLY one variable is required.
(Hint: If only one variable is required, this implies that you need to use Compound
Assignment operators)
The user wants you to note that these instructions would only work for ages determined this
year, and wants you
to specify it in the program.
(a.) Pick an integer between $0$ and $10$ ($0$ and $10$ exclusive).
(b.) Multiply the integer by two.
(c.) Add five to the result.
(d.) Multiply the result by fifty.
(e.) If you already had your birthday this year, add the result to one thousand, seven hundred
and seventy-two.
If you have not had your birthday this year, add the result to one thousand, seven hundred
and seventy-one. (valid for 2022, adjust accordingly after 2022)
(f.) Subtract your four-digit birth year from the result.
Run the code and display the output.
Explain your result.
(4.) A client wants you to develop a program to calculate the age of his child.
The instructions for the previous question still applies to this question.
However, in this case; the program will give the instructions to the child, and the child will
respond.
This program is an Input/Output program.
Develop a C# program for this child.
(5.) Program to determine your date of birth.
***Because your date of birth is a PII (Personal Identifiable Information), you may use a
fictitious age. However, you need to test it (privately) with your actual age to make sure it
works.
Develop a C# program to determine your date of birth based on these instructions.***
ONLY one variable is required.
(Hint: If only one variable is required, this implies that you need to use Compound
Assignment operators).
(a.) Pick the integer that is your month of birth.
(b.) Multiply the integer by two hundred.
(c.) Add three hundred and eighty two to the result.
(d.) Divide the result by two.
(e.) Add your day of birth to the result.
(f.) Multiply the result by 100.
(g.) Add thirteen thousand, eight hundred and forty to the result.
(h.) Add the last two digits of your year of birth to the result.
(i.) Subtract thirty two thousand, nine hundred and forty from the result.
Run the code and display the output.
Explain your result.
(6.) A client wants you to develop a program to calculate the date of birth of her child.
The instruction for the previous question still applies to this question.
However, in this case; the program will give the instructions to the child, and the child will
respond.
This program is an Input/Output program.
Develop a C# program for this child.
(7.) Develop a Body Mass Index (BMI) desktop application using the United States System.
Test each condition just like we did in our example for the United States System.
Address user-input errors.
(8.) Develop a Body Mass Index (BMI) console application using the International System.
The formula is on the screenshot.
Test each condition just like we did in our example for the United States System.
Address user-input errors.
(9.) Develop a Body Mass Index (BMI) desktop application using the International System.
The formula is on the screenshot.
Test each condition just like we did for the United States System.
Address user-input errors.
Questions (10.) and (11.) are meant to prepare you for the Midterm Project.
For Questions (10.) and (11.)
Develop a C# program that meets these requirements.
(I.) Consider any concept/scenario that uses conditional statements.
It will be great if you find a real-world application. However, you can make up your own.
If you decide to make up your own, please explain the scenario and the conditions well.
If you use a real-world application, please cite your source(s) accordingly. Explain the scenario and the conditions well.
Use at least two (two or more) different conditions.
The BMI Calculator has four different conditions.
But, please use any application that has at least two different conditions.
(II.) Accept user input(s).
(III.) Address user input errors.
(IV.) Test your program and display the result/output for each condition.
(V.) Test your program for user-input errors.
(VI.) Submit all the screenshots accordingly.
(10.) Develop a console application for your concept.
(11.) Develop a desktop application for your concept.
Textbook Questions
(12.) Question (6.) (needs Question 5) on Page 97
(13.) Question (8.) (needs Question 7) on Page 97
(14.) Question (12.) (needs Question 11) on Page 97
(15.) Question (14.) on Page 97
(16.) Question (16.) on Page 98
(17.) Question (2.) on Page 130
(18.) Question (4.) on Page 130
(19.) Question (6.) on Page 130
C# Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) C# Basic Declarations and Expressions : Exercises, Practice, Solution
(B.) C# Basic Algorithm: Exercises, Practice, Solution
(C.) C# Data Types : Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(20.) Please focus only on Questions that deals with Numbers and Operators.
Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
For those who do not mind messing around with several languages at the same time
Student: Excuse me, Mr. C
This course is only for C#
What do you mean?
Teacher: You are correct.
But, these subsequent questions are not for everyone.
That is the reason I am putting them at the end.
I have a question for you.
Have you ever seen any IT/Computer Science position that requires the knowledge of only one programming language?
Student: I have not checked, Sir.
Teacher: If you intend to be in the IT/Programming field for the long run, at least four (four or more)
languages are required.
If you look for IT positions at Indeed.com or other career/job websites, you will realize what I mean.
Search for c# programmer, you might be surprised that even for entry level positions
for a C# Programmer; they require you to have a working knowledge of several other programming languages.
Mr. C is preparing you for that...if you intend to work in the programming field for a long time.
Besides, this is a critical thinking approach.
I am required to develop and promote critical thinking questions for my students.
A programmer is basically a problem-solver irrespective of the programming language used to solve the problem.
Yes, we are working with C#.
However, if you find out that Java would be better in solving a particular problem in your workplace,
then you need to use Java unless your employer says otherwise.
The knowledge of several languages is a good asset. It makes you highly valuable.
Further, anyone who attempts any of the subsequent questions will still have to write the program in C# and get the same
result.
The questions and solutions are in another language.
But the student will have to write the program in C# and come up with the same solution. So, we are still on track.
It is critical thinking...multiple approaches to solving a question.
Be it as it may, these subsequent questions are not required.
It is okay even if you do not look at them. 😊
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) Java Math: Exercises, Practice, Solution
(B.) Java Basic Programming - Part 1: Exercises, Practice, Solution
(C.) Java Basic Programming - Part 2: Exercises, Practice, Solution
(D.) Java Data Types: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(21.) Please focus only on Questions that deals with Numbers and Operators.
Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in C#
Run the program. Please make sure your porgram output is the same solution
C++ Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) C++ Basic: Exercises, Practice, Solution
(B.) C++ Basic Algorithm: Exercises, Practice, Solution
(C.) C++ Math: Exercises, Practice, Solution
(D.) C++ Numbers: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(22.) Please focus only on Questions that deals with Numbers and Operators.
Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in C#
Run the program. Please make sure your program output is the same solution
(1.) Provide any of these if it is lacking in any DB post that solved any question in the
Assess tab of this module: Well-written comments; another approach/method to solving the
question; any additional relevant details; etc.
For Questions (3.) and (4.) in the Substantive Posts
Student: Mr. C, the instructions in Questions (3.) and (4.) are not correct.
The result is not my age.
How can you ask us to write a program that does not work?
(2.) Explain the result to the Student. (Answer this question only if any of your colleagues made a similar statement in the initial post.)
(3.) The Student wants only his/her age to be the result.
Without modifying any of the instructions (but using all of them) and one more instruction, extend the
program to display only the Student's age.
What is the extra instruction that you would include to work for all ages?
Write it. Run it.
For Questions (5.) and (6.) in the Substantive Posts
Student: Mr. C, I want the date of birth to display properly.
Teacher: Use a delimiter.
Student: What is a delimiter?
Teacher: A delimiter is a sequence of chararcters that specifies limits/boundaries of
characters in a text, expression, word, etc.
A good example is the forward slash that you can use to separate that DOB in the form of: mm/dd/yyyy.
The forward slash is a delimiter.
Another example is the pipe delimiter: mm | dd | yyyy.
Another example is the hyphen delimiter: mm-dd-yyyy.
Student: Okay, how do I display the result in that format?
(4.) Explain how you would display the result for the Student.
Write the code. Run it.
(5.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(6.) Other substantive responses.
This is the desktop application of the Standard Calculator
(1.) Please review the Functionalities of the Calculator and the Limitations of the Calculator as explained in
the Learn tab.
Maintain all the functionalities of the calculator.
Address any or all the limitations.
Submit some clear screenshots that maintains the functionalities.
Submit clear screenshots that addressed the limitations.
You may use my code if you wish
(in this case because you are extending the functionalities of my program) and/or your code.
(2.) The first standard calculator we programmed did not contain all the functions.
This is what we did.
This is what you should do.
Develop a calculator that contains all the functions enclosed with a red border besides the plus-minus button: $+/-$
In other words, the plus-minus button is not required.
However, all other functions enclosed within the red border are required.
Please note:
The C function is the Clear function. It deletes everything.
It clears the first number, operation, and the second number.
The CE function is the Clear Entries function. It deletes "some" things.
It clears only the second number. You can replace the second number and continue with the calculation.
It does not clear everything.
This is used when the entire calculation does not need to be deleted.
The BS (backspace) function (you may use alt+174 key if you prefer) is the backspace function.
It deletes part of the first number or the second number.
This is also used when the entire calculation does not need to be deleted.
Let us look at an example. You may test it.
$
\underline{Example} \\[3ex]
25 + 32 \\[3ex]
\color{red}{C} \;\; deletes\;\;everything \\[3ex]
\color{red}{CE} \;\; deletes\;\;only\;\;32 \\[3ex]
\color{red}{BS} \;\; deletes\;\;only\;\;2 \\[3ex]
$
This is the desktop application of the Scientific Calculator
(3.) We developed the scientific calculator.
However, it does not contain all the functions.
Develop the scientific calculator GUI that contains all the functions.
You may extend my application by adding the missing functions if you wish, or you may develop your own with all the functions.
You may use my code if you wish
(in this case because you are extending the functionalities of my program) and/or your code.
(4.) Develop a console application for an extension of the Body Mass Index (BMI) application example.
We did the application for the United States System (Customary System).
Extend the application by developing the calculator for the International System (Metric System).
The formula is on the screenshot.
Ask the user which system he/she wants to use to calculate the BMI.
Based on the user's selection, display the appropriate output.
Test all the conditions for both systems.
This is the desktop application of the BMI Calculator
(5.) Develop a desktop application for an extension of the Body Mass Index (BMI) application example.
We did the application for the United States System (Customary System).
Extend the application by including the calculator for the International System (Metric System).
The formula is on the screenshot.
Ask the user which system he/she wants to use to calculate the BMI.
Your desktop application should have the dropdown list for both systems, but should be null be default (using a ComboBox)
Alternatively, you may choose to use Radio Buttons.
Based on the user's selection, display the appropriate units for the weight and the height, as well as the output.
Test all the conditions for both systems.
Address user-input errors.
Question (6.) is meant to prepare you for the Midterm Project.
Develop a C# program that meets these requirements.
(I.) Consider any concept/scenario that uses conditional statements.
A real-world application is required. You may not make up your own.
Please cite your source(s) accordingly. Explain the scenario and the conditions well.
Use at least two (two or more) different conditions.
The BMI Calculator has four different conditions.
But, please use any application that has at least two different conditions.
(II.) Accept user input(s).
(III.) Address user input errors.
(IV.) Test your program and display the result/output for each condition.
(V.) Test your program for user-input errors.
(VI.) Submit all the screenshots accordingly.
(6.) Develop a console application and a desktop application for your concept.
character, string, Boolean, bool, concatenator operator, string concatenation, string interpolation, string literal, empty string, date, time, function, method, argument, escape sequences, dot member access operator,
Students will:
(1.) Discuss the C# string data type.
(2.) Discuss the C# Boolean data type.
(3.) Discuss Date and Time in C#.
(4.) Write programs that involves the String data type.
(5.) Write programs that involves the Boolean data type.
(6.) Write programs that involves Date and Time.
(1.) Textbook Chapter
(2.) Strings (C# Programming Guide) by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/)
(3.) System.String Class in .NET (VB and C#) by Microsoft
(https://docs.microsoft.com/en-us/dotnet/api/system.string?view=net-5.0)
Scroll down till you see Methods
(4.) How to (C#) by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/how-to/)
Scroll down till you see Working with strings
(5.) DateTime Struct by Microsoft
(https://docs.microsoft.com/en-us/dotnet/api/system.datetime?view=net-5.0)
Scroll down till you see Methods
(6.) Dates, Times, and Time Zones by Microsoft
(https://docs.microsoft.com/en-us/dotnet/standard/datetime/)
Focus on TimeZoneInfo and DateTimeOffset only (not TimeZone)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(7.) Type C# Strings and/or C# Booleans and/or C# Date and Time in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(8.) Type C# Strings and/or C# Booleans and/or C# Date and Time in the search bar and view/read the results.
A String is a sequence of ordered characters.
It is built out of characters.
It is enclosed in matching double quotation marks.
Remember the first C# program we wrote, the output...the message, THANK GOD.
That is an example of a string.
Let us review more examples of what we could do with C# strings.
Join Strings (Concatenate Strings)
Let us discuss several ways of joining strings (or concatenating strings).
Concatenate means to join or link together.
String concatenation is the joining of strings.
Please review the screenshots and the comments.
First Approach: String Concatenation using the Concatenator operator
The concatenator operator is the plus sign: +
Second Approach: String Interpolation
This uses the special character, $ (dollar sign), double quotes, and braces.
The braces are optional. However, they are required if the values of variables are to be included.
The variables are enclosed in braces.
Third Approach: String.Concat Method
This method is one of the .NET (C# and VB) system methods.
It concatenates two or three specified instances of String.
This implies that it can accept two or three arguments.
It will concatenate two strings if you enter two strings as the arguments.
It will concatenate three strings is you enter three strings as the arguments.
Fourth Approach: String.Join Method
This method is one of the Visual Basic methods. But it can be used for C# also.
It concatenates as many strings as you want.
This implies that it can accept several string arguments.
Notice the format of the fullName variable in the code
Student: Mr. C, must we use variables with all these approaches?
Teacher: Not at all.
You can use the strings directly rather than using variables.
In that case, for the String Interpolation; you would not need the braces.
String Escape Sequences are used to turn special characters into strings.
Sometimes, we write sentences that has the single quotation marks and the double quotation marks.
How do we display such sentences in a C# program?
We have to use the backslash escape sequence
There are several escape sequences. Please see the List of String Escape Sequences
Also, check out: Escape Sequences
In this module, we shall focus on the use of the Backslash escape sequence.
As we make progress, we may use some more escape sequences.
Let us demonstrate the use of the backslash escape sequence in inserting single quotes, double quotes, and backslash in
sentences.
Insert single quote, double quote, backslash in sentences
Teacher: What are you looking at?
You already know.
Student tries to hide it.
Teacher: I want to ask you something.
Look at it.
Please turn it off...remember the course syllabus.
Before you turn it off, do you see two numbers in the Power off button?
Student: Numbers?
I do not see numbers.
It's an icon.
Teacher: Yes, they are numbers.
The numbers are: $0$ and $1$
$1$ is inside the $0$ in most devices.
Student: Interesting.
Teacher: $0$ represents OFF
$1$ represents ON
You see these two numbers in almost all electronic devices (tablets, smartphones, computers) including some
electric switches.
In Logic, $0$ represents FALSE
$1$ represents TRUE
We use true and false Boolean values in Statements including conditional statements and
iterative statements. We shall cover Statements in the next module.
The use of these two numbers: $0$ and $1$ in Mathematics and Computer Science to repesent FALSE and
TRUE values is known as Boolean Algebra
It was developed by George Boole, an English mathematician/philospher/logician.
We can also use these Boolean numbers $0$ and $1$ to represent choices/options of NO and YES
A Boolean is a fundamental data type in C# that:
(1.) is declared with the keyword, bool or Boolean
However, it is recommended to use the bool keyword.
The bool keyword represents the Boolean data type.
(2.) can represent only one of two states: True or False
(3.) gives an output of only one of two values: True or False
(4.) is used for comparison (in relational/comparison operators) to compare expressions.
(5.) is used in statements (conditional statements and iterative statements) to make decisions.
A Boolean Expression is an expression that returns a Boolean value.
Let us demonstrate some examples of the use of Booleans.
Booleans: Example 1
Booleans: Example 2
Student: Mr. C, why is it better to use the bool keyword?
The Boolean keyword has the same functionality. Right?
Teacher: That is correct.
However, the bool keyword is used to denote the Boolean data type
Just as the string keyword is used to denote the String data type
Just as the int keyword is used to denote the Integer data type
Date and time stamps are needed for: transactions, receipts, appointments, agreements, events, rules/laws, and
tickets (by cops and troopers) among others.
Besides, we shall use the date and time functions in the midterm project.
Notable Notes on C# Date and Time
(1.) Date is a data type (Value Type) in .NET standard (C# and VB) declared as DateTime
(2.) You can also use the var keyword (variable) to declare it.
We shall be using the var keyword as applicable.
(3.) It covers the date and time range from: 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 31, 9999
(4.) It is an object of the DateTime Structure.
(5.) It has several constructors, properties, methods, and operators.
If you did not understand Numbers (4.) and (5.), do not worry.
I shall explain more in the comments in the screenshots.
(6.) For all arithmetic operations (especially Addition and Subtraction operations) involving Date and Time, please use
only the built-in operators.
This is important to avoid getting errors (especially errors of undercounting or overcounting by 1, 0.1, 0.001)
The built-in operators are: .Add, .Subtract, etc.
Do not use the "usual" arithmetic operators.
This is what I mean.
For example: to determine the number of days of the sum of two dates:
Do: example1.Date.Add(example2.Date).Days;
Do Not: (example1.Date + example2.Date).Days;
For example: to determine the number of days of the difference between two dates:
Do: example1.Date.Subtract(example2.Date).Days;
Do Not: (example1.Date - example2.Date).Days;
Before we continue, let us review the format specifiers for displaying date and time in .NET (C# and VB)
Format Specifier | Description | Example for the U.S (en-US) |
---|---|---|
"d" | Short date pattern | 3/1/2021 |
"D" | Long date pattern | Monday, March 1, 2021 |
"f" | Full date/time pattern (short time) | Monday, March 1, 2021 12:30 PM |
"F" | Full date/time pattern (long time) | Monday, March 1, 2021 12:30:40 PM |
"g" | General date/time pattern (short time) | 3/1/2021 12:30 PM |
"G" | General date/time pattern (long time) | 3/1/2021 12:30:45 PM |
"M", "m" | Month/day pattern | March 1 |
"t" | Short time pattern | 12:30 PM |
"T" | Long time pattern | 12:30:45 PM |
"O", "o" | Round-trip date/time pattern | 2021-03-01T12:45:30.0000000-07:00 |
"R", "r" | RFC1123 pattern | Monday, 1 Mar 2021 12:30:45 GMT |
"s" | Sortable date/time pattern | 2021-03-01T12:30:45 |
"u" | Universal sortable date/time pattern | 2021-03-01 12:30:45Z |
"U" | Universal full date/time pattern | Monday, March 1, 2021 12:30:45 PM |
"Y", "y" | Year month pattern | March 2021 |
My Preferred Approach
I think this is the easiest approach.
(1.) Declare a String variable for the Full date/time pattern (long time)
For example: string currentDateTime = DateTime.Now;
(2.) To get only the date; use the code: currentDateTime.ToLongDateString();
(3.) To get only the time; use the code: currentDateTime.ToLongTimeString();
Or if you really like writing short codes (short form):
(1.) string currentDate = DateTime.Now.ToLongDateString();
(2.) string currentTime = DateTime.Now.ToLongTimeString();
Alternatively:
(1.) Begin by using the Full date/time pattern (long time)
Declare a DateTime variable to store the current date and time using the Full date/time pattern (long time)
For example: DateTime currentDateTime = DateTime.Now;
(2.) To get only the date; use the code within a String Interpolation: currentDateTime.ToLongDateString();
(3.) To get only the time; use the code within a String Interpolation: currentDateTime.ToLongTimeString();
Please see the implementation of this approach in the screenshots for the Birthday Application.
There are several date/time format methods that you can use with that variable.
Just type the variable and press the dot access member operator (the decimal point button on your keyboard) and
start reviewing the list of methods you can use.
You can also press the dot access member operator and press "T" (ToString methods) so you can see more methods.
Have fun exploring 😊
There are several approaches to handling dates and times in C#
Let us discuss some of them.
As at today: 03/01/2021; Kent State University has 8 Ohio campuses, several other U.S campsuses, and four campuses outside
the United States otherwise known as Kent State Worldwide.
Kent State Worldwide consists of Kent State in Florence, Italy; Geneva, Switzerland; New Delhi, India; and Beijing, China.
Mr. C wants to greet all his students in the United States and Worldwide.
He wants to great them in their local dates and times.
He would kindly ask you, his student (please check out one of the Questions in the Assess tab) to teach him the greeting in your language.
But his work right now is to display the Full date/time pattern (long time) of each country: United States, Italy,
Switzerland, India, and China.
Because we shall be working with foreigh countries, it is necessary to include: using System.Globalization namespace
To get the current local date and time (date and time according to the user's computer system), the syntax is:
DateTime currentDateTime = DateTime.Now;
To get the local date and time of the user (say in the United States), the syntax is:
var dateTimeUSA = currentDateTime.ToString("F", CultureInfo.CreateSpecificCulture("en-US"));
where:
USA is the country (you can replace with your country)
dateTimeUSA is the variable name (you can use any appropriate name you prefer)
"F" is the format specifier for the Full date/time pattern (long time) (you can use any format specifier you like)
CultureInfo.CreateSpecificCulture("en-US") is the System command/code for displaying the full date and time in United States English language.
The specific culture is en-US
en is English Language
US is the United States
Just as: CultureInfo.CreateSpecificCulture("es-MX") is the code to display the full date and time in Mexican Spanish Language.
The specific culture is es-MX
es is Spanish Language
MX is Mexico
So, the command follows the syntax:
CultureInfo.CreateSpecificCulture("specific culture")
This is the
List of Countries, Languages, and Specific Culture for Displaying Date and Time
(https://www.samdomforpeace.com/References/ASCII.html#specificCulture)
But, there is an issue.
The issue is displaying the current times in other countries.
The specific culture works for displaying the dates and times in the languages (several languages) of different countries as
applicable
However, we still need to display the actual times (not the local user's time) for any country as applicable
Moreover, depending on the time of the day in each country, the dates might be incorrect as well.
In other words, we want to greet each Kent State University student according to his/her country's time/time zone (not according to my time/time zone)
We want to display the current date and time of each country that has Kent State University campus.
So, we need the time zone names and IDs of different countries
As at today: 03/05/2021 the time zone names and IDs of several countries in .NET are:
Names and IDs of Time Zones for Different Countries
Note that these time zone IDs should be entered as strings.
If a country is not listed, then we will need to find the UTC (Universal Time Coordinated) and the offset
as applicable.
Then, we look up any country with the same UTC and offset that is listed, and use that country.
How?
Bing or Google "time zone for country and look for the UTC time zone of the country that is mot listed.
If it is UTC+4, then find an applicable country that has UTC+04:00 and use that country.
Alternatively, contact Microsoft and ask them to include your country/city/county/province/region.
Say we want to display the current date and time in Mexico City, we look up the time zone name and ID:
Guadalajara, Mexico City, Monterrey => Central Standard Time (Mexico)
We convert the local user's date and time (local user is in the United State) using the code:
var dateTimeMEX = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentDateTime, destinationTimeZoneId: "Central Standard Time (Mexico)")
Then, we use the specific culture to get the date and time in Mexican Spanish
var dateTimeMexico = dateTimeMEX.ToString("F", CultureInfo.CreateSpecificCulture("es-MX"))
Please review the screenshots and the comments.
Date and Time: Example 1: Current Date and Time in Different Countries
Student: What if we want to display the date and time in several states across the United States?
Our students come from all 50 states of the United States as well as the United States territories.
And you know there are different time zones in the United States.
How do we display the current date and time in those states in their respective time zones?
Teacher: Very good question.
In that case, we have to get the current date and time of the user
DateTime currentDateTime = DateTime.Now;
Then, we use the specific culture of each state to get the current date and time in that state.
For example; say we want the current date and time in the State of Ohio
The specific culture for the State of Ohio is en-OH
The code will then be:
DateTime dateTimeOhio = currentDateTime.ToString("F", CultureInfo.CreateSpecificCulture("en-OH"));
This is the List of the States and Territories of the United States for Displaying Date and Time
(https://www.samdomforpeace.com/References/ASCII.html#specificCultureUS)
Student: So, we do not use the TimeZoneInfo class like we did for foreign countries?
Teacher: We do not.
Because it is the U.S.A 😊
But, we can if we want to. We just have to find the appropriate destination ID
But it is much simpler to just use the specific culture for the date and time for the states and territories of the
United States.
Let's develop another date and time function application.
What are some of your memorable events? dates for those events?
Student: Birthday, Christmas...I'm always looking forward to it
Teacher: Let's write a program in that regard.
I shall use my birthday as an example.
Let us calculate how many days there are until my birthday.
We shall begin with a console application.
Then we shall develop a desktop application and explore more toolbox controls.
An interesting toolbox control to explore is the Timer.
Have you noticed those websites where you see a Timer that displays a countdown of the times: days and
hours:minutes:seconds to a particular event?
Student: Yes, I have.
Teacher: Cool. So, we shall explore that control and some other controls for the GUI.
As at today: 03/02/2021, my birthday is yet to occur. However, it is important to add a functionality to the program to display a
message to the user if the user's birthday has already occurred prior to today.
Student: I guess we shall ask the user to enter the birthday?
Teacher: Yes. Let's use an Input/Output feature to make it interactive.
The program will ask the user to enter the birth year, birth month, and birth day.
If the birthday has occurred, inform the user accordingly. Then, display a positive message informing the user
that we look forward to his/her next "age" birthday.
If the birthday is yet to occur, display the number of days remaining until the birthday.
If the user's birthday is today, we shall greet the user with a HAPPY BIRTHDAY greeting.
This will require a conditional statement.
Student: You know Mr. C, we have been using Statements since Module 3 when we are supposed to cover it in
Module 5.
Teacher: That is correct. It goes to show how important they are in programming.
It is okay to introduce you to them so you get familiar with using them.
We shall cover them in detail in Module 5. It is a broad topic.
Please review the screenshots and the comments.
Date and Time: Example 2: Birthday Application
Let us develop a desktop application of the Birthday app.
We are gradually learning these toolbox controls as we make progress in the course.
We shall work with two additional controls in this section: the MonthCalendar control and the Timer control
The MonthCalendar Control allows us to select a date from a calendar.
(https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/monthcalendar-control-windows-forms?view=netframeworkdesktop-4.8)
According to Microsoft: the Windows Forms MonthCalendar control presents an intuitive graphical interface for users to view
and set date information.
The control displays a grid containing the numbered days of the month, arranged in columns underneath the days of the week.
You can select a different month by clicking the arrow buttons on either side of the month caption.
The additional control we shall use is the Timer control.
The Timer Control
is a control that determines how an application responds after a certain amount of time passes.
(https://docs.microsoft.com/en-us/powerapps/maker/canvas-apps/controls/control-timer)
It is an object of the Timer Class
(https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=net-5.0)
Please review the desktop applications we developed in previous modules.
Form1.cs: Adjust and Align
(Name) property: Leave as is. Do not change
Text property: Birthday App © 2021 SamDom4Peace Designs (Sample)
BackColor property: Web: Cyan
Font: property: Font: Times New Roman; Font Style: Regular; Size: 18
FormBorderStyle property: Fixed3D
MaximizeBox property: False
The MaximizeBox property is set to False if we do not want the user to maximize the application.
The reason is because we want the interface to have a consistent look.
Toolbox Controls | Property |
---|---|
MonthCalendar: Adjust and Align | (Name): BirthDateMonthCalendar |
Button: Adjust and Align |
Text: &Birthday Message BackColor: Web: White (Name): BirthdayButton Cursor: Hand |
Copy and Paste Button: Adjust and Align |
Text: E&xit (Name): ExitButton |
RichTextBox: Adjust and Align | (Name): MessageRichTextBox |
Label: Adjust and Align |
AutoSize: False Set this property first Text: Delete label1 and write Days, Hours:Minutes:Seconds (Name): TimerLabel TextAlign: MiddleCenter Font: Font: Times New Roman; Font Style: Regular; Size: 48 |
Timer: Adjust and Align |
Enabled: True Interval: 1000 The interval is the frequency of elapsed events in milliseconds We set it to 1000 because 1000 millisecond = 1 second (Name): BirthdayTimer |
Design Area
Access keys: B for the Birthday Mesage button and x for the Exit button
When the form loads, we do not want to see the label that has the timer
When the user's birthday is today, we do not want to see the label that has the timer.
When the user already had his/her birthday this year, we do not want to see the label that has the timer.
When the user is yet to have his/her birthday this year, we want to see how many days, how many hours, how many minutes,
and how many seconds until the user's birthday this year.
(1.) Double-click any empty space on the form in the Design window.
This leads to the Code window
Scroll a little bit to the top, write the comments, and begin to...
(2.) Write the code.
Let us use a top-down approach.
Double-click each button in the Design window to open the Code window.
Then write the code for the event: what should happen when the user clicks the button?
Please review the screenshots.
Review the comments.
Program Code
Run the Program
Student: I have several questions.
Teacher: Please go ahead.
Student: Line #159 in the code: \t, what is it?
Teacher: It is an escape sequence that represents a horizontal tab space
Student: The second result: which is correct: 109 days until your birthday versus 108 days, 6 hours,
34 minutes, and 51 seconds?
Teacher: What do you think?
Which one is more accurate?
Student: The second one I guess.
Teacher: Yes, the second one is more accurate.
The first one is rounded (an estimate)
If you do a quick seearch on Bing or Google for: how many days until Christmas, you will see the first one
The second one is accurate.
Those are the results from two different websites.
Student: My next question deals with the same Line #159 in the code
I guess that goes back to the second question.
Teacher: That is correct.
Using time.days (time from the Timespan data type) is more accurate that using daysBirthday
(days from the difference of the DateTime data type variables)
Student: The next question: You basically used the same code you wrote for the Button_click event for the
Timer_Tick event?
Is there not a way to reuse codes without having to copy and paste each time?
Teacher: Very good observation and very good question.
I did it because we are yet to cover Functions
Of course, one of the advantages of functions (both system-defined functions and user-defined functions) is for code reusability.
I would have used a user-defined function for the application had we covered Functions before now.
You may use strings not written in English language. However, if you use any language other than English language,
please make sure you translate it. Your colleagues and I need to understand any language you use.
Insensitive words or any word deemed inappropriate to any race, gender, religion, and national origin among others are
unacceptable. Any violation will not yield any point.
If you are not sure of the words/string to use, please contact me first.
Remember DB 3 Requirement. There are enough functions for everyone. If all the functions are done, please
attempt another question.
.NET (VB and C#) String Methods: Part 1 (Examples are written in C#) Less work
Please review the:
System.String Class in .NET (VB and C#) by Microsoft
(https://docs.microsoft.com/en-us/dotnet/api/system.string?view=net-5.0)
Scroll down till you see Methods
(1.) Pick any four methods besides the ones I discussed
Write the code examples for each method and implement each of them.
Run your codes.
Display the results.
VB String Methods: Part 2 (Examples are written in VB) A little extra work because you need to write in C#
Please review the:
String Functions in Visual Basic
(https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/functions/string-functions)
(2.) Pick any four methods besides the ones I discussed
Write the code examples for each method and implement each of them.
Run your codes.
Display the results.
DateTime Structure
Please review the:
DateTime Struct by Microsoft
(https://docs.microsoft.com/en-us/dotnet/api/system.datetime?view=net-5.0)
Scroll down till you see Methods
(3.) Pick any four methods besides the ones I discussed
Write the code examples for each method and implement each of them.
Run your codes.
Display the results.
(4.) Please review the Date and Time example in this module.
Our students come from the entire 50 states of the United States and its territories.
However, the United States has different time zones.
Find out/browse/learn/discover the different time zones in the United States and its territories as seen in the
The Official U.S. Time (https://time.gov/) according to the
National Institute of Standards and Technology
Include those time zones in your comments.
Display the current date and time for each time zone.
Verify your answer with the times and time zones on that website.
C# Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) C# Strings : Exercises, Practice, Solution
(B.) C# Date and Time: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(5.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
For those who do not mind messing around with several languages at the same time
Student: Excuse me, Mr. C
This course is only for C#
What do you mean?
Teacher: You are correct.
But, these subsequent questions are not for everyone.
That is the reason I am putting them at the end.
I have a question for you.
Have you ever seen any IT/Computer Science position that requires the knowledge of only one programming language?
Student: I have not checked, Sir.
Teacher: If you intend to be in the IT/Programming field for the long run, at least four (four or more)
languages are required.
If you look for IT positions at Indeed.com or other career/job websites, you will realize what I mean.
Search for c# programmer, you might be surprised that even for entry level positions
for a C# Programmer; they require you to have a working knowledge of several other programming languages.
Mr. C is preparing you for that...if you intend to work in the programming field for a long time.
Besides, this is a critical thinking approach.
I am required to develop and promote critical thinking questions for my students.
A programmer is basically a problem-solver irrespective of the programming language used to solve the problem.
Yes, we are working with C#.
However, if you find out that Java would be better in solving a particular problem in your workplace,
then you need to use Java unless your employer says otherwise.
The knowledge of several languages is a good asset. It makes you highly valuable.
Further, anyone who attempts any of the subsequent questions will still have to write the program in C# and get the same
result.
The questions and solutions are in another language.
But the student will have to write the program in C# and come up with the same solution. So, we are still on track.
It is critical thinking...multiple approaches to solving a question.
Be it as it may, these subsequent questions are not required.
It is okay even if you do not look at them. 😊
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) Java Strings: Exercises, Practice, Solution
(B.) Java Date and Time: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(6.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in C#
Run the program. Please make sure your program output is the same solution
C++ Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) C++ Strings: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(7.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in C#
Run the program. Please make sure your program output is the same solution
(1.) Review the post (Discuss Questions) done by your colleagues.
Use a different string method to work on the same string used by your colleague.
(2.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(3.) Other substantive responses.
You may use strings not written in English language. However, if you use any language other than English language,
please make sure you translate it. Your colleagues and I need to understand any language you use.
Insensitive words or any word deemed inappropriate to any race, gender, religion, and national origin among others are
unacceptable. Any violation will not yield any point.
If you are not sure of the words/string to use, please contact me first.
We are yet to do Statements (in the next Module), but you can give this question a try.
A string palindrome is a word, phrase, clause or sequence of characters that is
spelled and read the same way backward and forward.
In other words, when one reads it as is, reverses it and reads it again; the pronunciation is the same.
Examples include the:
Words: HANNAH, BOB, madam, level, civic, racecar, rotor
Phrase: never odd or even
Clause: nurses run
Sentence: Was it a car or a cat I saw?
(1.) Write a C# program that asks for user input.
Determine if the user input is a string.
If the user input is not a string, ask the user to enter only a string.
If the user input is a string, determine if it is a string palindrome.
Inform the user whether it a string palindrome or not.
Test at least one example of: Words, Phrase, Clause, and Sentence that was listed.
This implies that you should test at least four examples.
(2.) Please review the Date and Time: Example 1: Current Date and Time in Different Countries
Extend my application by greeting your fellow colleagues in the langauge of their countries.
Because Visual Studio did not display the Hindi and Chinese alphabets, do not worry about India and China.
Write a C# application that:
(a.) Displays the current date and time for the countries: United States, Italy, and Switzerland.
Because you are extending my application, you may use my code.
Find out/browse/learn/discover the greetings for Good Morning, Good Afternoon, and Good Evening for Italy and
Switzerland in Italian and German respectively.
(b.) Displays the greetings to each user (your fellow colleague) according to their countries (the current times in their countries).
If the time is between 12:00:01 AM to 12:00:00 PM (inclusive), greet Good Morning in each langauge.
If the time is between 12:00:01 PM to 04:00:00 PM (inclusive), greet Good Afternoon in each lanaguage.
If the time is between 04:00:01 PM to 12:00:00 PM (inclusive), greet Good Evening in each language.
You may use 12-hour or 24-hour time formats.
These are the minimum requirements. You are welcome to add more functionalities.
(3.) Please review the Date and Time example in this module.
Our students come from the entire 50 states of the United States and its territories.
However, the United States has different time zones.
Find out/browse/learn/discover the different time zones in the United States and its territories as seen in the
The Official U.S. Time (https://time.gov/) according to the
National Institute of Standards and Technology
Include those time zones in your comments.
Display the current date and time for each time zone.
Greet each user (your fellow colleague) according to their time zones (their own current times).
If the time is between 12:00:01 AM to 12:00:00 PM (inclusive), greet Good Morning.
If the time is between 12:00:01 PM to 04:00:00 PM (inclusive), greet Good Afternoon.
If the time is between 04:00:01 PM to 12:00:00 PM (inclusive), greet Good Evening.
You may use 12-hour or 24-hour time formats.
These are the minimum requirements. You are welcome to add more functionalities.
(4.) Please review the Date and Time: Example 2: Birthday Application
Modify my application or write your new application.
(a.) Ask the user to also enter the time (hh:mm:ss) in hours, minutes, and seconds that he/she was born.
(b.) If the user has not had birthday this year, inform the user about the number of days, hours, minutes, and seconds
until his/her birthday.
Do not stress about the calculations. Microsoft.NET methods handle most of these calculations.
(c.) If the user already had birthday this year, or if today is the user's birthday; display appropriate positive
messages to the user.
(d.) A user's birthday is 29th February. This implies that the user has to celebrate birthdays only on leap years
(years that are divisble by 4). Accommodate that user in your application. Display message(s) accordingly.
(e.) Include checks for user-input errors and display messages accordingly.
(5.) Write a C# program that solves Question (8.) on the
Applications of Numbers website.
(https://numbersandnotations.appspot.com/numbersApplications.html)
Use any actual date that is a Tuesday.
Ensure that the output of your program corresponds to the solution on the website.
Please display: the actual date, the actual day, the new date and the new day in your output.
In other words, I am looking for the input date that corresponds to a Tuesday, the input day that is the Tuesday,
the output date that corresponds to a Friday, and the output day that is the Friday.
Please check to ensure your program gives the correct output (result).
You may develop a console application or a desktop application for this program.
Submit screenshots of the question, your program, and the output of your program.
(6.) Please review the GUI Programming: Birthday Application
We developed the Birthday desktop application using the MonthCalendar control.
Another option is to use the DateTimePicker Control
(https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.datetimepicker?view=net-5.0)
The DateTimePicker control allows the user to select a date and a time and to display the date and time with a specified format.
The advantage of the DateTimePicker control over the MonthCalendar control is the ability of the user to select only a date and a time.
The advantage of the MonthCalendar control over the DateTimePicker is that it allows the user to select only dates
(one date or a range of dates) without selecting time.
In the comments for that program: Lines #48 and #49, I ask that you extend the application.
Develop a desktop application that meets these requirements.
(a.) Ask the user to also enter the time (hh:mm:ss) in hours, minutes, and seconds that he/she was born.
You may use the DateTimePicker control or any other toolbox control you prefer.
(b.) If the user has not had birthday this year, inform the user about the number of days, hours, minutes, and seconds
until his/her birthday.
Do not stress about the calculations. Microsoft.NET methods handle most of these calculations.
(c.) If the user already had birthday this year, or if today is the user's birthday; display appropriate positive
messages to the user.
(d.) A user's birthday is 29th February. This implies that the user has to celebrate birthdays only on leap years
(years that are divisble by 4). Accommodate that user in your application. Display message(s) accordingly.
(e.) Include checks for user-input errors and display messages accordingly.
(7.) Develop a traffic light desktop application using C#
(a.) You may use the Panel toolbox control
(https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.panel?view=net-5.0) and/or your own appropriate pictures with
the PictureBox toolbox control
(https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.picturebox?view=net-5.0)
for the lights: Green, Yellow, and Red.
(b.) Set the timer for the duration of the yellow light to be at least two seconds (two seconds or more) before it turns to red.
(c.) Use any appropriate time durations for the green light and the yellow light.
(d.) You are welcome to add more functionalities.
(8.)
statement, flow control, flow of execution, statement block, nested blocks, declaration statements, expression, expression statements, control flow statememts, selection statements: if, else, swich, case; iteration statements: do, for, foreach, in, while; jump statements: break, continue, default, goto, return, yield; exception handling statements: throw, try-catch, try-finally, try-catch-finally; checked and unchecked statements, await statement, yield return statement, fixed statement, lock statement, labeled statements, empty statement, top-level statements, using statement, conditional statements, decision-making statements, decisions, looping statements, loops, repetitive statements, branching statements, branches,
Students will:
(1.) Discuss Statements in C# programming language.
(2.) Write selection statements.
(3.) Write iteration statements.
(4.) Write jump statements.
(5.) Write some exception handling statements.
(6.) Write programs that solve real-world problems using statements.
(7.) Complete the Midterm Project on Piecewise Functions.
(1.) Textbook Chapter
(2.) Statements (C# Programming Guide) by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/statements)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(3.) Type C# Statements in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(4.) Type C# Statements in the search bar and view/read the results.
(5.) Top-level Statements by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/exploration/top-level-statements)
(6.) using statement (C# Reference) by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement)
A statement is an individual instruction of a program.
It ends with a semicolon.
It forms a complete unit of execution.
It is equivalent to a sentence in a language.
It can consist of a single line of code (single-line statement).
It can also consist of multiple lines of code (multi-line statements) in a block, known as a statement block.
A statement block is enclosed in curly braces {} and can contain nested blocks.
A block is a group of zero or more statements between balanced curly braces that can be used where a single statement
is allowed.
In Example 3 (If-else statement) as seen in the screenshot below; the if statement is the
first block of code and the else statement is the second block of code.
The order in which statements are executed in a program is called the flow of control otherwise known as
flow of execution.
The flow of control varies every time a program is run.
It depends on how the program reacts to the instruction it receives at run-time.
There are several types of statements in C#
We have discussed some of them in previous modules.
We shall discuss some of them in this module.
We shall discuss some of them in subsequent modules.
As at today: 03/12/2021; the statements in C# are:
(1.) Declaration Statement
A declaration statement declares a variable or constant.
To declare a variable, the data type must be specified as well. You have the option of assigning a value to it.
To declare a constant, the keyword must be specified. A value must be assigned to it.
// Declaration statement
// We started using this statement beginning from Module 2
int num1 = 7;
(2.) Expression Statement or Expression
An expression statement or an expression is a construct made up of variables, operators, and method invocations,
which are constructed according to the syntax of the language, that evaluates to a single value.
Expression statements calculate a value must store the value in a variable.
// Expression statement
// We covered this statement in Module 3
double result = 7 * (5 - 2);
Control Flow Statements
Generally, statements in C# are executed from top to bottom, in the order that they appear.
However, control flow statements control the order in which statements are executed.
In other words, they break up the flow of the execution of statements by using decision making, looping, and
branching; thereby allowing a program to execute particular blocks of code conditionally.
They include:
(3.) Selection Statements or Conditional statements or Decison-making Statements or Decisions
A selection statement allows the user to branch to different code sections depending on one or more conditions.
They are the: if statement, if-else statement, if-then statement,
if-then-else statement, Multiple ifs statement, and the switch statement.
(4.) Iteration Statements or Looping Statements or Loops
An iteration statement allows the user to perform the same set of statements repeatedly until a specified condition is met.
It also allows the user to loop through collections such as arrays.
They are the: for loop, foreach loop, while loop, and the do-while loop statements.
(5.) Jump Statements or Branching Statements or Branches
A jump statement allows the user to transfer control to another section of the code.
They are the: break statement, continue statement, goto statement, return statement,
and the default statement.
Let us discuss the Selection, Iteration, and Jump statements.
Then, we can discuss more statements.
if (condition) { statement; }C# ignores whitespaces so you can also write it this way:
if (condition) { statement; }
if (condition) { statement; } else { statement; }C# ignores whitespaces so you can also write it this way:
if (condition) { statement; } else { statement; }We can also write simple If-else statement using the Ternary operator
variable = if (condition) ? statement if true : statement if false;(3.) If-else if-else statement
if (condition 1) { statement; } else if (condition 2){ statement; } else if (condition 3) { statement; } else { statement; }Whitespaces are ignored in C#. Therefore you can also write it this way:
if (condition 1) { statement; } else if (condition 2) { statement; } else if (condition 3) { statement; } else {statement; }Keep in mind that we do not specify condition 4 in the code for the else statement because we already know that the else statement would only be executed if all the other prior conditions are not met.
if (condition 1) { statement; } if (condition 2){ statement; } if (condition 3) { statement; } if (condition 4) { statement; }Whitespaces are ignored in C#. Therefore you can also write it this way:
if (condition 1) { statement; } if (condition 2) { statement; } if (condition 3) { statement; } if (condition 4) { statement; }Review the Definitions of Numbers
variable switch (variable) { case 1: statement; break; case 2: statement; break; case 3: statement; break; default: statement; }Case 1
$52$ is not a String variable.
Besides, it is not one of those defined cases.
So, it falls in the default label.
Therefore, the statement in the default label is the output.
Question $2$
(2.) The user entered "africa" and expected to see the statement associated with that continent.
However, the user saw another output.
Explain.
africa is not the same as AFRICA based on case-sensitivity.
Hence, the statement in the default label is displayed.
Recall the Piecewise Function program we wrote earlier.
We used Conditional statements to write it.
Let us develop the same program using the Switch statement.
We shall use the Switch statement and the Ternary operator to write the program.
Piecewise Function Application using the Switch Statement and the Ternary Operator
dataType variable; if condition 1 { If condition 2 { statement; } else { statement; } } else if condition 3 { if condition 4 { statement; } else { statement; } } else { statement; }Notice the order in which each nested conditional statement is closed.
for (initializer; condition; iterator) { statement; }This is also written as:
for (variable = beginValue; condition; variable compound_assignment someValue) { statement; }where the:
for
keyword begins the For loop. It is required. initializer
is the beginning value of the variable. It can be optional. condition
is the condition required for the variable to reach the final value. It can be optional. iterator
is the incremental or decremental value for the beginning value of the variable to reach the final value.
It can be optional. initializer; while (condition) { statement; iterator; }This is also written as:
variable = beginValue; while (condition) { statement; variable compound_assignment someValue; }where the:
while
keyword begins the While loop. It is required. initializer
is the beginning value of the variable. It can be optional. condition
is the condition required for the variable to reach the final value. It can be optional. iterator
is the incremental or decremental value for the beginning value of the variable to reach the final value.
It can be optional. initializer; do { statement; iterator; } while (condition);This is also written as:
variable = beginValue; do { statement; variable compound_assignment someValue; } while (condition);where the:
do
keyword begins the Do-While loop. It is required. initializer
is the beginning value of the variable. It can be optional. condition
is the condition required for the variable to reach the final value. It can be optional. iterator
is the incremental or decremental value for the beginning value of the variable to reach the final value.
It can be optional. while
keyword ensures that the condition is being met. It is required. foreach (var item in collection) { statement; }We shall implement the foreach statement in Module 7 (Arrays).
The midterm project is designed to assess your knowledge of Statements in solving real-world problems.
It is a Piecewise Function application.
Any other application will not considered.
Please:
(1.) Visit my website on: Piecewise Functions
(www.piecewise-functions.appspot.com)
(2.) Read the Story to understand the idea of Piecewise functions.
(3.) Read the Overview of Piecewise Functions for more understanding of Piecewise functions.
(4.) Study the Applications of Piecewise Functions
(5.) Review the Project Examples. Ensure you follow all the instructions and directions.
(6.) Review the Midterm Project rubric for your course.
(7.) Complete the Midterm Project for your course.
(8.) Ask questions. I can help.
If you have any issue at any time and you have reviewed the resources I provided and you cannot fix the issue,
please attend the Office Hours/Live Sessions so I can help you.
(9.) Include all these: (documentation of all your Math work and the .exe file) in OneDrive, create a
shareable link, and post the link in the Midterm Project Drafts forum of the course on Blackboard or send to me via email.
You may also upload them directly if you prefer.
I shall review and provide feedback.
(10.) When you are done with your project:
Make sure your executable file runs by itself outside the project folder
If it does run, include these three items: single executable file (that runs by itself outside the folder), the
Math documentation (Word document that has the Math part), and the entire project folder, into a folder,
zip the folder (.zip extension only) and submit it in the appropriate area of the Blackboard course.
If it does not run, please fix it.
If you cannot fix it, please attend the Office Hours/Live Sessions so I can help you.
NOTE: Any actual project submitted to me via email will not be graded.
If you wish to save some time for research:
Please review the Piecewise Function projects done by my previous students.
The direct link of the verifiable websites are included.
(I.) VB Projects
(II.) C# Projects
(III.) C++ Projects
(IV.) Java Projects
You may not do any same application done by any of my previous students for C#
You may do any Piecewise Function application not done by any of my previous students for C#.
If you are not sure what project you may or may not do, please contact me via the school email.
method, function, main method, system pre-defined method, user-defined method, common language runtime (CLR), method signature, method name, method parameter, parameter list, method access, access level, public, private, abstract, sealed, return value, return type, void, method invocation, instance method, static method, argument, argument list, pass parameters by value, pass parameters by reference (ref keyword), parameter arrays, extension methods, async methods, expression-bodied members, expression body definitions, iterators, modifier, local variables, return keyword, value parameters, reference parameters, pass parameters by output (out keyword), pass parameters by input (in keyword),
Students will:
(1.) Discuss methods.
(2.) Pass parameters to methods (Pass by Value, Pass by Reference).
(3.) Pass arguments to methods (Pass by Position, Pass by Name).
(4.) Overload methods.
(5.) Write programs that solves real-world problems using methods.
(1.) Textbook Chapter
(2.) Methods (C# Programming Guide) by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods)
(3.) Methods in C# by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/methods)
(4.) out parameter modifier by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier)
(5.) in parameter modifier by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/in-parameter-modifier)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(6.) Type C# Methods or C# Functions in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(7.) Type C# Methods or C# Functions in the search bar and view/read the results.
// Method using System; namespace Methods { class Program { // Declare the method: SumNumbers // Parameters are: num1 and num2 public static int SumNumbers(int num1, int num2) { return num1 + num2; } static void Main(string[] args) { // Call the method // Arguments are 5 and 7 SumNumbers(5, 7); // Print what you called Console.WriteLine(SumNumbers(5, 7)); } } }In user-defined method:
int result = SumNumbers(5, 7);
Console.WriteLine(result);
[accessLevel] static void MethodName(parameterList)
{
statements;
Console.WriteLine($"something");
}
[accessLevel] static dataType MethodName(parameterList)
{
statements;
return something;
}
Celsius Temperature to Fahrenheit Temperature Conversion
Given: The Human Body Temperature in Celsius Temperature ($37^\circ$)
To Calculate: The Fahrenheit Temperature
Formulas:
$
fahrenheitTemp = \dfrac{9 * celsiusTemp}{5} + 32 \\[5ex]
$
Fahrenheit Temperature to Celsius Temperature Conversion
Given: The Human Body Temperature in Fahrenheit Temperature ($98.6^\circ$)
To Calculate: The Celsius Temperature
$
celsiusTemp = \dfrac{5 * (fahrenheitTemp - 32)}{9} \\[5ex]
$
Teacher: Did you notice the difference?
Student: Yes...I think so
I prefer the Void type method
We can easily use the variable names rather than writing the value. I mean ...
I would prefer to use the variable: fahrenheitTemp rather than 98.6
Teacher: I prefer the void method too
It helps if we want to return multiple values along with a message in a String Interpolation
Let us write a code example that uses an Input/Output feature.
We shall also demonstrate the use of local variables.
Formulas:
$
fahrenheitTemp = \dfrac{9 * celsiusTemp}{5} + 32 \\[5ex]
celsiusTemp = \dfrac{5 * (fahrenheitTemp - 32)}{9} \\[5ex]
$
Discriminant of a Quadratic Trinomial (no worries, we do not discriminate in Mathematics 😊)
Calculate the Discriminant of a Quadratic Trinomial in General Form
(1.) Program Requirement
Every line of executable code in any C# application must be inside some method.
(2.) Reusability: write one time, use several times
Methods are useful for performing repeated or shared tasks such as frequently used calculations, text and control
manipulations, and database operations.
We can just define a method one time, and then reuse the statements inside the method as many times as we want
whenever we call that method.
(3.) Easier Code Readability and Faster Debugging
Imagine a "big" program (program with long lines of codes).
Methods allow such programs to be broken into discrete logical units.
This helps for easier code readability and faster debugging.
(4.) Avoiding Code Duplication
After developing a method in one program, it can be reused in another program with little or no modifcation.
There are two ways to pass parameters to a method in C#
They are:
(1.) Pass by Value (Value Parameters)
In the previous examples we did for the Void type and Data type methods; we passed parameters by value because the
default passing mechanism is to pass parameters by value.
(2.) Pass by Reference (Reference Parameters)
When we pass parameters by reference, we use the ref keyword before the data type in the parameter variable as well
as before its corresponding argument.
As we learned earlier:
When we declare a method, we use parameters.
When we call the method, we use arguments.
In C#, a paramter can be passed to a method by value or by reference
Passing Mechanism is the passing of a parameter to a method by value or by reference.
It determines whether the method can modify the programming element underlying the argument in the calling code.
Please note that passing mechanism is optional in method declarations.
The default passing mechanism in C# (when the passing mechanism is not specified) is to pass parameters by value.
Passing Parameter By Value | Passing Parameter By Reference (ref keyword) |
---|---|
(1.) Protection: Exposure of calling variables to change The advantage of passing a parameter by value is that it protects a variable from being changed by the method. |
(1.) Protection: Exposure of calling variables to change The advantage of passing a parameter by reference is that the method can return a value to the calling code through that argument. |
(2.) Performance: For a value data type, C# copies the entire data contents of the
argument. This implies that for a large value type such as a structure, it can be less efficient to pass it by value. For a reference data type, C# copies only the pointer to the data (which is four bytes on 32-bit platforms and eight bytes on 64-bit platforms). So, performance is not an issue when an argument is passed by value for a reference data type. |
(2.) Performance: For a value data type, C# copies the entire data contents of the
argument. This implies that for a large value type such as a structure, it can be more efficient to pass it by value. For a reference data type, C# copies only the pointer to the data (which is four bytes on 32-bit platforms and eight bytes on 64-bit platforms). So, performance is not an issue when an argument is passed by reference for a reference data type. |
(3.) If the calling code element underlying the argument is a nonmodifiable element, declare the corresponding parameter
by value. No code can change the value of a nonmodifiable element. |
(3.) If the procedure needs to change the underlying element in the calling code, declare the corresponding parameter by reference. |
(4.) If the underlying element is modifiable, but you do not want the procedure to be able to change its value;
declare the parameter by value. Only the calling code can change the value of a modifiable element passed by value. |
(4.) If the correct execution of the code depends on the procedure changing the underlying element in the calling code, declare the parameter by reference. |
Definitions:
A local variable is a variable declared within a method.
A member variable is a variable declared inside a class or structure,
but not within any method internal to that class or structure.
We shall focus on only local variables in this module.
Student: Mr. C, if I say I did not understand the passing mechanism you just explained, I mean it.
I want to learn and understand it, rather than just memorize.
Is there any way you can break it down?
Teacher: Yes, let's do some examples.
Student: Alright, but please use a simple example.
You have been using Mathematics examples.
Can you explain this time with English...say using Strings?
Teacher: Okay. Not a problem. Let's do the examples.
Pass Parameters by Value: Example $1$
Pass Parameters by Reference: Example $1$
Student: So, when we pass parameters by value, the arguments are printed; and when we pass paramaters by
reference, the parameters (rather than the arguments) are printed.
Is that correct?
Teacher: That is correct.
When we pass parameters by value (which is the default passing mechanism when the passing mechanism is not specified),
the copies of the parameters (which is the arguments) are printed.
The actual parameters are not affected.
Only the arguments (which are the copies of the parameters) are printed.
When we pass parameters by reference, the actual parameters are affected because the actual parameters become associated
with the arguments passed to the function.
Would you like for us to do another example?
Student: Yes please.
But keep it simple.
Teacher: Okay. Let's do an example with numbers.
Pass Parameters by Value: Example $2$
Pass Parameters by Reference: Example $2$
Student: I get it now.
But, what if we decided to print the values in the user-defined method rather than the main method?
Teacher: Then the program will print the parameters in that user-defined method
Student: Regardless of the passing mechanism?
Teacher: Yes...
Provided you did not print anything in the Main Method
So, this is what happens
When the user-defined method is called in the main method, the program will head to the user-defined method and execute every
statement there.
So it will print whatever it sees there
And head back to the main method
And if it sees there is no print command in the main method, it will not print anything on the console.
Parameters passed by Reference can further be passed by output or passed by input
Let us discuss them.
Passing by Reference (ref) | Passing by Output (out) | Passing by Input (in) |
---|---|---|
(1.) It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument. |
(1.) It is a passing by reference. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument. |
(1.) It is a passing by reference. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument. |
(2.) Requires that the variables passed in as arguments be initialized before being passed in a method call. However, the called method may assign a value or modify the argument. (See Number (3.)) |
(2.) Does not require the variables passed in as arguments to be initialized before being passed in a method call. |
(2.) Requires that the variables passed in as arguments be initialized before being passed in a method call. However, the called method may not assign a value or modify the argument. (See Number (3.)) |
(3.) Allows the called method to modify the argument value. ref arguments may be modified. |
(3.) The called method must modify the argument value. out arguments must be modified by the called method. |
(3.) Does not allow the called method to modify the argument value. in arguments cannot be modified by the called method. |
(4.) Both the method definition (declaration) and the calling method must explicitly use the ref keyword. | (4.) Both the method definition (declaration) and the calling method must explicitly use the out keyword. | (4.) The method definition (declaration) must use the in keyword. However, the calling method must not use it. |
The ref, out, and in keywords are not part of the method signature for the purpose of
overload resolution. This implies that methods cannot be overloaded if the only difference is that one method takes a ref or in argument and the othee takes an out argument. |
We have seen the two ways we can pass parameters.
Let us discuss the two ways we can pass arguments.
When we call a Method, we can pass the arguments by position or by name
In the examples we did so far, we passed the arguments by position.
Passing Arguments by Position is passing the arguments in the order in which they appear in the method's
declaration when we defined the parameters.
It is delimited (separated) by commas
You can omit an argument when you call the method if you made it optional with the corresponding parameter.
However, if you do; it's place must be held with a comma.
Passing Arguments by Name is passing the arguments without regard to position.
They can be passed in any order. However, we must specify the
name of the parameter followed by a colon followed by the value of the argument
(parameterName: argumentValue)
You can omit an argument when you call the procedure if you made it optional with the corresponding parameter.
But the nice thing about this approach is that you do not have to use commas to denote missing positional arguments.
Another nice feature about this approach is that you do not have to follow the order in which the parameters were defined
in the method.
Further, this approach makes it easier to note which arguments you are passing and which ones you are omitting.
Remember when we used this approach... in Module 4 when we covered Date and Time methods
Let us write some code examples.
Pass Arguments by Position Example
Pass Arguments by Name Example
For all applicable questions, please:
(A.) Use the Void type and/or the Data type as your method
(B.) Use appropriate method names in line with C# naming conventions.
(C.) Include an appropriate message with your result.
(D.) Use an Input/Output feature if you wish.
(1.) Using the Data Type Method Example: Input/Output Feature, include a condition that asks the user if the
quadratic trinomial is in general form.
If the user says No, ask the user to arrange the quadratic trinomial in general form before proceeding.
Then, quit the program.
If the user says Yes, proceed to run the program.
Test both conditions.
Textbook Questions
(2.) Question 2. on Page 303
(3.) Question 4. on Page 303
(4.) Question 6. on Page 304
(5.) Question 10. on Page 303
Arithmetic: Questions (6.) through (9.)
Please review the Definitions of Numbers on Numbers website:
Numbers and Notations
(https://numbersandnotations.appspot.com/#definitions)
Please make sure you indicate the type of number in your comments.
(6.) Write a method that prints any of those types of numbers between one and thirty ($1$ and $30$ are included)
(7.) Write a method that prints the first thirty numbers of any of those types of numbers.
Focus on the first positive thirty numbers of those kind of numbers.
(8.) Write a method that asks the user to input two values (those values could be
positive, zero or negative)
The method should print all the numbers for any of those types of numbers between those two
values.
Those two values should be included if they are part of those type of numbers.
(9.) Write a method that asks the user to put in a value (that value could be positive, zero,
or negative)
The method should print thirty values of those types of numbers up to and including the
user-input value.
Geometry: Questions (10.) and (11.)
Please review the Mensuration Formulas on Mensuration website:
Mensuration
(https://www.samuelchukwuemeka.com/Mensuration/mensuration.html)
Please make sure you indicate the type of figure/shape in your comments.
(10.) Write a method that asks the user to input the required parameters for any
two-dimensional figure.
The method should return the area and perimeter of that figure.
(11.) Write a method that asks the user to input the required parameters for any three-dimensional figure.
The method should return the surface area and volume of that figure.
Strings/Quotes: Questions (12.) and (13.)
Find a quote from any of your favorite authors or your favorite quote.
If you do not have any favorite author or a favorite quote, make up a quote yourself, and
indicate that it is your own quote.
(12.) Write a method that prints all the vowels in that quote, and returns the count.
(13.) Write a method that prints all the consonants in that quote, and returns the count.
C# Programming Exercises, Practice, Solution by W3Resource
Please review:
C# Function: Exercises, Practice, Solution
(https://www.w3resource.com/csharp-exercises/function/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(14.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
For those who do not mind messing around with several languages at the same time
Student: Excuse me, Mr. C
This course is only for C#
What do you mean?
Teacher: You are correct.
But, these subsequent questions are not for everyone.
That is the reason I am putting them at the end.
I have a question for you.
Have you ever seen any IT/Computer Science position that requires the knowledge of only one programming language?
Student: I have not checked, Sir.
Teacher: If you intend to be in the IT/Programming field for the long run, at least four (four or more)
languages are required.
If you look for IT positions at Indeed.com or other career/job websites, you will realize what I mean.
Search for c# programmer, you might be surprised that even for entry level positions
for a C# Programmer; they require you to have a working knowledge of several other programming languages.
Mr. C is preparing you for that...if you intend to work in the programming field for a long time.
Besides, this is a critical thinking approach.
I am required to develop and promote critical thinking questions for my students.
A programmer is basically a problem-solver irrespective of the programming language used to solve the problem.
Yes, we are working with C#.
However, if you find out that Java would be better in solving a particular problem in your workplace,
then you need to use Java unless your employer says otherwise.
The knowledge of several languages is a good asset. It makes you highly valuable.
Further, anyone who attempts any of the subsequent questions will still have to write the program in C# and get the same
result.
The questions and solutions are in another language.
But the student will have to write the program in C# and come up with the same solution. So, we are still on track.
It is critical thinking...multiple approaches to solving a question.
Be it as it may, these subsequent questions are not required.
It is okay even if you do not look at them. 😊
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
Java Methods: Exercises, Practice, Solution
(https://www.w3resource.com/java-exercises/method/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(15.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in C#
Run the program. Please make sure your program output is the same solution
(1.) Review the post (Discuss Questions) done by your colleagues.
Use a different statement to work on the same function used by your colleague.
For example: if your colleague used an iteration statement in a function, you may use a conditional statement or a
jump statement or a different iteration statement to write the same function to give the same output.
(2.) Review the post (Discuss Questions) done by your colleagues.
Use a different method to display the same output of the program done by your colleague.
For example: if your colleague used the Data type method, use the Void type method to write the program to
display the same output.
You may include an appropriate message along with the output.
(3.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(4.) Review the post (Discuss Questions) done by your colleagues.
If your colleague used the Void type method to display several values of different data types in an output, use the
Passing parameters by Output (out) approach to display the same output.
(5.) Other substantive responses.
Algebra:
Please review the Roots of a Quadratic Equation on the Expressions and Equations website:
Quadratic Equations
(www.expressions-equations.appspot.com/#quadraticEquations)
There is a calculator I developed that calculates the roots of a quadratic equation and displays a message.
(1.) Console Application
(2.) Desktop Application
(I.) Write a method that requests the user to input the three values: (as seen on my calculator), and
display the same message that is displayed by my calculator.
In other words, the output and message from your calculator should be the same as the output and
message from my calculator when the user inputs those three values.
Test your program for each of the four cases of the discriminant regarding the nature of the roots
of a quadratic equation as seen in Numbers (1a.), (1b.), (2.) and (3.) on my website.
(II.) Submit clear screenshots of your program.
(III.) Submit clear screenshots of the output of your program for the four cases.
(IV.) Submit clear screenshots of the output of my calculator for the four cases.
(III.) and (IV.) should display the same messages.
(3.)
array, single-dimensional array, one-dimensional array, dimension, rank, data structure, array type, array elements, square brackets, index, array index, array length, sort array, System.Linq namepsace, arrays as parameters, arrays as arguments, array methods, new keyword, object keyword, var keyword, ListBox, MultiLine TextBox, parallel arrays,
Students will:
(1.) Discuss arrays.
(2.) Implement some array methods.
(3.) Pass arrays as function parameters.
(4.) Pass arrays as arguments.
(5.) Write programs that use arrays to solve real-world problems.
(1.) Textbook Chapter
(2.) Arrays (C# Programming Guide) by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/)
(3.) Tuple Types (C# Reference) by Microsoft
(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(4.) Type C# Array and/or C# Tuple in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(5.) Type C# Array and/or C# Tuple in the search bar and view/read the results.
/* elements are not specified elements are the same data type */ dataType[] arrayName; /* elements are not specified elements are the same data type array size is specified */ dataType[] arrayName = new dataType[arraySize]; /* elements are specified, separated by comma elements are the same data type */ dataType[] arrayName = {array elements}; /* elements are specified, separated by comma elements are the same data type array size is specified */ dataType[] arrayName = new dataType[arraySize] {array elements}; /* elements are not specified elements are of different data types */ object[] arrayName; /* elements are not specified elements are of different data types array size is specified */ object[] arrayName = new object[arraySize]; /* elements are specified, separated by comma elements are of different data types */ object[] arrayName = {array elements}; /* elements are specified, separated by comma elements are of different data types array size is specified */ object[] arrayName = new object[arraySize] {array elements}; /* elements are specified elements are of the same or different data types */ var arrayName = new[] {array elements}; /* elements are specified elements are of the same or different data types array size is specified */ var arrayName = new[arraySize] {array elements};(3.) When an array is created, the number of dimensions and the length of each dimension are established.
array[index] = element;
ForEach Loop | For Loop, While Loop, Do-While Loop |
---|---|
(1.) Loops through each array element without using a counter. | (1.) Loops through each array element using a counter. |
(2.) The length of the array is not needed. | (2.) The length of the array is needed. |
Example 2: Create an array of strings of size 4
Print the array.
Print the fourth element of the array
Sort the array
Print the sorted array.
Print the fourth element of the sorted array.
Student: Mr. C
Just to be sure...
Because sometimes you declare several variables
And sometimes you use only variable
It can be confusing at times
So, the same variable that you used in the array and the sorted array: name
You used it because it was declared inside the loop?
So, it is only known within the loop? It is not known outside the loop...is that right?
Teacher: That is correct
Student: So, if I try to use that variable outside the loop, the program will not recognize it?
Teacher: That is correct
Student: But why did you not declare several variables like you did in the previous example?
Teacher: It is just a choice
You can declare several variables if you wish.
Let us do an input-output feature.
Let us also demonstrate the use of an array that stores values of different data types.
Example 3: Input-Output Feature for a Pizza Restuarant
Statistics comprises Data Analysis.
Data Analysis is part of Data Science.
Data Science is part of Computer Science/Programming.
As a programmer, it is very likely that you will deal with data.
In this course, we shall focus only on some of the Descriptive Statistics of Data Analysis.
The Descriptive Statistics that we shall discuss in this course are:
(1.) Measures of Center:
Also known as the Measures of Central Tendency
They are the: Mean, Median, Mode, and Midrange.
(2.) Measures of Spread:
Also known as the Measures of Dispersion or the Measures of Variability or the Measures of Variation
For this course, we shall focus on the: Range, Variance, and Standard Deviation.
(3.) Measures of Position:
Also known as the Measures of Location
For this course, we shall focus on the: Five Number Summary of Data
They are the: Minimum, First Quartile, Second Quartile, Third Quartile, and Maximum.
The First Quartile is also known as the Lower Quartile or the 25th Percentile
The Second Quartile is also known as the Median or the Middle Quartile or 50th Percentile
The Third Quartile is also known as the Upper Quartile or 75th Percentile
C# has some predefined methods used for calculating some of these measures.
We shall calculate the rest of the measures.
Let us write program examples of descriptive statistics using C#
The formulas used are the formulas on the Descriptive Statistics website
(1.) Formulas for the Measures of Center
(2.) Formulas for the Measures of Variation
(3.) Formulas for the Measures of Location
Example 4: Data Analysis: Descriptive Statistics of Raw Ungrouped Data with C#
Reviewing the code in Example 4: Data Analysis: Descriptive Statistics of Raw Ungrouped Data with C#
Line #23: we used the system-defined Length
method for the user-defined array: dataset
This determines the length (size) of the array.
Line #26: we used the system-defined Array class method: Array.Sort
which takes in the user-defined array:
dataset
as the argument.
This method sorts the array in ascending order.
Line #182: we used the system-defined Array class method: Array.Sort
which takes in the user-defined array:
dataset
as the argument.
This method sorts the array in descending order.
Let us begin with Line #23
Explore all the system-defined methods of the user-defined array as seen in this image
Scroll down and explore each method.
Then onto Line #26
Please review the methods of the Array class
Scroll down till you see Methods
Notice I implemented the Array.Sort method
Explore the implementation of the other methods of the Array class.
For Line #182
This is another implementation of the methods of the Array class.
Because we need to calculate the upper quartile according to
this formula,
we had to sort the array in descending order.
ListBox, Buttons, RichTextBox, Another C# Form
In previous modules, we explored the use of Button and RichTextBox
In this module, let us explore the use of the ListBox
The ListBox is a toolbox control that contains a list of selectable items.
The ListBox accepts only the string data type by default (in a String Collection Editor), just like the TextBox and
the ComboBox.
However, we will need to convert the ListBox into an Array.
To do this, we need to cast the data in the ListBox to a string, then to an Array.
The code used to do this is:
var data = DatasetListBox.Items.Cast<string>().ToArray();
Notice we used the var keyword to declare the variable: data
Say we want to work with integers, we will then need to convert the array of strings into an array of integers.
The code used to convert an array of strings to an array of integers is:
int[] dataset = data.Select(int.Parse).ToArray();
Items can be entered into the ListBox directly in the Design Form or from the Code window or from the Button
and another Toolbox Control.
Let us enter the items directly.
Let us do Question (13.) on the Solved Examples on the Measures of Center website
We are not using Data Bound Items so we leave that box unchecked.
In this example, we shall:
(1.) Use a ListBox to include the elements of the array
(2.) Use Buttons to respond to user-event to calculate the descriptive statistics (each of the measures)
(3.) Write methods (user-defined methods only) to calculate the descriptive statistics.
(4.) Call each method under each button event accordingly.
(5.) Use a RichTextBox in another Form to display the results.
Form1.cs: Adjust and Align
(Name) property: Leave as is. Do not change
Text property: Descriptive Statistics (Data Already Entered)
BackColor property: Web: PeachPuff
Font: property: Font: Times New Roman; Font Style: Regular; Size: 18
FormBorderStyle property: Fixed3D
MaximizeBox property: False
The MaximizeBox property is set to False if we do not want the user to maximize the application.
The reason is because we want the interface to have a consistent look.
But you may set your preference.
Toolbox Controls | Property |
---|---|
ListBox: Adjust and Align | (Name): DatasetListBox |
Button: Adjust and Align |
Text: Measures of &Center BackColor: Web: White (Name): CenterButton Cursor: Hand |
Copy and Paste Button: Adjust and Align |
Text: Measures of &Spread (Name): SpreadButton |
Copy and Paste Button: Adjust and Align |
Text: Measures of &Position (Name): PositionButton |
Copy and Paste Button: Adjust and Align |
Text: &Descriptive Statistics (Name): StatisticsButton |
RichTextBox: Adjust and Align | (Name): MessageRichTextBox |
Design Area
Access keys: C for the Measures of Center button, S for the Measures of Spread button,
P for the Measures of Position button, and D for the Descriptive Statistics button
(1.) Click the View menu and click the Code tab View → Code, or press the F7 function key on your Windows keyboard
or double-click any empty space on the form in the Design window.
This leads to the Code window
Scroll a little bit to the top, write the comments, and begin to...
(2.) Write the code.
We shall write methods for calculating the Measures of Center, Measures of Spread, and the Measures of Position.
Then, we call the method respectively when the user clicks the button for each of them.
For example:
When the user clicks the Measures of Center button, the method for calculating the measures of center is called, the measures
of center are calculated, and displayed in the RichTextBox.
When the user clicks the Measures of Spread button, the method for calculating the measures of spread is called, the measures
of spread are calculated, and displayed in the RichTextBox.
When the user clicks the Measures of Position button, the method for calculating the measures of position is called,
the measures of position are calculated, and displayed in the RichTextBox.
But:
When the user clicks the Descriptive Statistics button, the methods for calculating all the measures are called,
all the measures are calculated, and displayed in another form
Let us go ahead and add the second form.
Form2.cs: Adjust and Align
(Name) property: Leave as is. Do not change
Text property: Descriptive Statistics (Results of Data Already Entered)
BackColor property: Web: PeachPuff
Font: property: Font: Times New Roman; Font Style: Regular; Size: 18
FormBorderStyle property: Fixed3D
MaximizeBox property: False
The MaximizeBox property is set to False if we do not want the user to maximize the application.
The reason is because we want the interface to have a consistent look.
But you may set your preference.
RichTextBox: Adjust and Align
(Name) property: StatisticsRichTextBox
ForeColor property: Web: DarkBlue
Modifiers property: Public This is very important
To access the RichTextBox in Form 2 from the Button in Form 1, the Modifiers property must be set to Public
Please review the screenshots.
Review the comments.
Program Code
Run the Program
Student: I have several questions.
Teacher: Okay, go ahead.
Student: First: why did you declare doubles when the dataset contains only integers?
Teacher: Doubles take care of integers... well if you do not declare Option Strict On
Here is what I like about C# and VB (something Java does not do...unfortunately)
If you declare the integers and the answer as doubles, and the answer ends up being an integer; C# and VB.NET will
display them as integers.
So, C# and VB will accept them as doubles (even though they are integers) and will also dsiplay the answer as an
integer if the answer is an integer (even though you declared the answer as a double)
On the other hand, Java will accept them as doubles and will also display the answer as a double. Java will also throw
a fit if you declare them as doubles and declare the answer as an integer. In that case, it will require you to convert
it (cast it) as an integer.
So, when working with VB and C#; it is very okay if you declare the data and the answer as doubles even if they are
integers.
Besides, what if you have a mixture of integers and doubles in the dataset?
It is much safer to declare them as doubles.
Student: It seems Java is unforgiving
Teacher: It is not just unforgiving of mistakes. It is very unforgiving of mistakes.
It is very particular about everything.
Student: VB seems to be the really nice one.
Teacher: VB is very nice.
However, it is lenient to a fault.
For example; you can declare numbers as integers enclosed in quotations marks, and add those numbers in VB.
Student: Really?
Teacher: Yes
VB will think you probably made a mistake by enclosing the numbers in quotation marks and will go ahead, treat them
as numbers, and add them.
That is definitely not good.
Student: I guess that makes C# the win-win
Teacher: Hmmmm... I might disagree
All programming langauges have their pros and cons.
For someone who wants to learn a friendly lanaguage, the person should begin with VB
However, if the person intends to learn other languages such as C, C++, C#, Java; the person should probably not begin with
VB
VB syntax is very different from C# and Java.
The person should begin with C#
This is because C# "falls in the middle" of VB and Java
C# has some similar methods with VB because of the .NET configuration. It also has similar syntax with Java.
Anyone who learns C# will easily learn VB and will not struggle with learning Java
Student: What if the person begins with Java?
Teacher: Then the person should be determined not to quit.
What is your next question?
Student: In this example, you used the in-built Average() method to get the mean.
But you used a for-loop in the console application to get the mean.
You decided to do things differently?
Teacher: Very good observation.
Notice Line #6 in the desktop application: using System.Linq;
It has the pre-defined method to calculate the average
It is automatically included in the desktop application but not in the console application
To use it in the console application, we have to include it by writing the command: using System.Linq;
Student: My next question...
What if the user decides to enter the data?
Teacher: You mean: a user-entered data rather than an already-entered (pre-defined) data?
Student: Yes Sir
Teacher: Let us do the example.
Would you like for us to begin with a console application or a desktop application for the example?
Student: Let us begin with a desktop application because we are already discussing it.
Teacher: Okay.
In that case, we shall need a MultiLine TextBox
It is actually the regular TextBox.
Remember, the TextBox enables the user to enter text.
Further, it provides multiline editing and password character masking.
In this case, we shall check the box that says MultiLine.
Let's do it.
int[] arrayIntegers = Array.ConvertAll(MultiLineTextBox.Lines, new Converter<string, int>(int.Parse));In this example, we shall:
Form1.cs: Adjust and Align
(Name) property: Leave as is. Do not change
Text property: Descriptive Statistics (User will enter data)
BackColor property: Web: Lavender
Font: property: Font: Times New Roman; Font Style: Regular; Size: 18
FormBorderStyle property: Sizable as is
MinimizeBox property: True as is
MaximizeBox property: True as is
We want the user to be able to adjust the application to accommodate the sample size of the data.
TextBox: Adjust and Align
(Name): DataTextBox
Button: Adjust and Align
Text: Measures of &Center
BackColor: Web: White
(Name): CenterButton
Cursor: Hand
Copy and Paste Button: Adjust and Align
Text: Measures of &Spread
(Name): SpreadButton
Copy and Paste Button: Adjust and Align
Text: Measures of &Position
(Name): PositionButton
Copy and Paste Button: Adjust and Align
Text: &Descriptive Statistics
(Name): StatisticsButton
Copy and Paste Button: Adjust and Align
Text: C&lear Dataset
(Name): ClearButton
Copy and Paste Button: Adjust and Align
Text: E&xit Application
(Name): ExitButton
Form2.cs: Adjust and Align
(Name) property: Leave as is. Do not change
Text property: Descriptive Statistics of Data Entered by User
BackColor property: Web: Lavender
Font: property: Font: Times New Roman; Font Style: Regular; Size: 18
RichTextBox: Adjust and Align
(Name) property: StatisticsRichTextBox
ForeColor property: Web: DarkBlue
Modifiers property: Public This is very important
Design Area
Access keys: C for the Measures of Center button, S for the Measures of Spread button,
P for the Measures of Position button, D for the Descriptive Statistics button,
l for the Clear Dataset button, and x for the Exit Application button.
(1.) Click the View menu and click the Code tab View → Code, or press the F7 function key on your Windows keyboard
or double-click any empty space on the form in the Design window.
This leads to the Code window
Scroll a little bit to the top, write the comments, and begin to...
(2.) Write the code.
We shall write methods for calculating the Measures of Center, Measures of Spread, and the Measures of Position.
Then, we call the method respectively when the user clicks the button for each of them.
For example:
When the user clicks the Measures of Center button, the method for calculating the measures of center is called, the measures
of center is calculated, and displayed in the RichTextBox on the second form.
When the user clicks the Measures of Spread button, the method for calculating the measures of spread is called, the measures
of spread is calculated, and displayed in the RichTextBox on the second form.
When the user clicks the Measures of Position button, the method for calculating the measures of position is called, the measures
of position is calculated, and displayed in the RichTextBox on the second form.
When the user clicks the Descriptive Statistics button, the methods for calculating all the measures are called, all the measures
are calculated, and displayed in the RichTextBox on the second form.
Let us do Question (45.) on the Solved Examples on the Measures of Center website
Remember that this application with the MultiLine TextBox will allow the user to enter the data values directly.
Please review the screenshots.
Review the comments.
Program Code
Run the Program
For Questions (1.) and (2.);
Review these Sorting Techniques and Algorithms
(https://www.samdomforpeace.com/DataStructures/Sorting.html)
(1.) Write a method (user-defined method) that sorts an array in ascending order using any of the techniques.
Use an array size of at least 3 (array size $\ge 3$).
Specify the technique.
(2.) Write a method (user-defined method) that sorts an array in descending order using any of the techniques.
Use an array size of at least 3 (array size $\ge 3$).
Specify the technique.
(3.) Write a method (user-defined or system-defined method) that divides an even-sized unsorted array into two equal halves, sorts the
first half in ascending order, and sorts the second half in descending order.
Use any even size of at least 8 (array size $\ge 8$).
(4.) Write a method (user-defined or system-defined method) that divides an even-sized unsorted array into two equal halves, sorts the
first half in descending order, and sorts the second half in ascending order.
Use any even size of at least 8 (array size $\ge 8$).
TextBook Questions
(5.) Question 2 on Page 260
(6.) Question 4 on Page 260
(7.) Question 8 on Page 261
(8.) Please review the Solved Examples on the Measures of Center
Find any question that has a dataset that can be entered into an array.
(a.) Write a program that computes the measures of center for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(9.) Please review the Solved Examples on the Measures of Spread
Find any question that has a dataset that can be entered into an array.
(a.) Write a program that computes the measures of dispersion for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(10.) Please review the Solved Examples on the Measures of Position
Find any question that has a dataset that can be entered into an array.
(a.) Write a program that computes the measures of location for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(11.) Please review the Solved Examples on Descriptive Statistics
Find any question that has a dataset that can be entered into an array.
(a.) Write a program that computes the measures of center and/or the measures of variability and/or the measures of position for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
C# Programming Exercises, Practice, Solution by W3Resource
Please review:
C# Array: Exercises, Practice, Solution
(https://www.w3resource.com/csharp-exercises/array/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(12.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
(13.) Please review the system-defined methods for a user-defined array.
Besides the one I implemented in Example 4: dataset.Length; on Line #23, implement any other two methods.
(14.) Please review the methods of the Array class
(https://docs.microsoft.com/en-us/dotnet/api/system.array?view=netcore-3.1)
Scroll down till you see Methods
Besides the one I implemented in Example 4: Array.Sort(dataset); on Line #26, implement any other two methods.
For those who do not mind messing around with several languages at the same time
Student: Excuse me, Mr. C
This course is only for C#
What do you mean?
Teacher: You are correct.
But, these subsequent questions are not for everyone.
That is the reason I am putting them at the end.
I have a question for you.
Have you ever seen any IT/Computer Science position that requires the knowledge of only one programming language?
Student: I have not checked, Sir.
Teacher: If you intend to be in the IT/Programming field for the long run, at least four (four or more)
languages are required.
If you look for IT positions at Indeed.com or other career/job websites, you will realize what I mean.
Search for c# programmer, you might be surprised that even for entry level positions
for a C# Programmer; they require you to have a working knowledge of several other programming languages.
Mr. C is preparing you for that...if you intend to work in the programming field for a long time.
Besides, this is a critical thinking approach.
I am required to develop and promote critical thinking questions for my students.
A programmer is basically a problem-solver irrespective of the programming language used to solve the problem.
Yes, we are working with C#.
However, if you find out that Java would be better in solving a particular problem in your workplace,
then you need to use Java unless your employer says otherwise.
The knowledge of several languages is a good asset. It makes you highly valuable.
Further, anyone who attempts any of the subsequent questions will still have to write the program in C# and get the same
result.
The questions and solutions are in another language.
But the student will have to write the program in C# and come up with the same solution. So, we are still on track.
It is critical thinking...multiple approaches to solving a question.
Be it as it may, these subsequent questions are not required.
It is okay even if you do not look at them. 😊
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
Java Array: Exercises, Practice, Solution
(https://www.w3resource.com/java-exercises/array/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(15.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in C#
Run the program. Please make sure your program output is the same solution
C++ Programming Exercises, Practice, Solution by W3Resource
Please review:
C++ Array: Exercises, Practice, Solution
(https://www.w3resource.com/cpp-exercises/array/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(16.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in C#
Run the program. Please make sure your program output is the same solution
JavaScript Programming Exercises, Practice, Solution by W3Resource
Please review:
JavaScript Array: Exercises, Practice, Solution
(https://www.w3resource.com/javascript-exercises/javascript-array-exercises.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(17.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in C#
Run the program. Please make sure your program output is the same solution
JavaScript Programming Exercises, Practice, Solution by W3Resource
Please review:
JavaScript Searching and Sorting Algorithm: Exercises, Practice, Solution
(https://www.w3resource.com/javascript-exercises/searching-and-sorting-algorithm/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(18.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in C#
Run the program. Please make sure your program output is the same solution
(1.) Review the post (Discuss Questions) done by your colleagues.
Use a different statement to work on the same Array or the same Tuple used by your colleague.
For example: if your colleague used an iteration statement in an array, you may use a conditional statement or a
jump statement or a different iteration statement to write the same Array or the same Tuple to give the
same output.
(2.) Review the post (Discuss Questions) done by your colleagues.
Use a different data structure to display the same output of the program done by your colleague.
For example: if your colleague used an Array, use a Tuple to write the program to display the same output.
(3.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(4.) Review the post (Discuss Questions) done by your colleagues.
Use a different user-defined array method and/or system-defined array class method to work on the same program
done by your colleague.
(5.) Other substantive responses.
TextBook Questions
(1.) Question 10 on Pages 261 and 262
(2.) Please review Example 3: Input-Output Feature for a Pizza Restaurant
Please do these tasks.
(a.) Modify the application to include the name and slogan of the restaurant in the customer's receipt.
In other words, Lines #12 - 16 should be included in the customer's receipt on the condition that those lines should be written
only one time in the project but called twice. Do you understand what I mean? We did that concept in Module 6
Submit the screenshots for the code and the output.
(b.) Samuel entered an order for a customer.
He noticed that the total cost for that customer was less than similar orders he gave past customers.
So, he reviewed his entries and noticed that he mistakenly entered "extra cheese" rather than "Extra Cheese".
He did not realize that the application was data entry case-sensitive.
He met with his manager and asked her to reconsider the application.
The manager contacted you, the programmer; and informed you about the concern.
Using at least five different sentences, address this issue.
Consider the fact that the manager is not a programmer.
Inform the manager of several options/applications and suggest the best option.
Asking the manager to ensure that all her employees are properly trained on case-sensitive data entry is not considered
an option in this case.
Write your responses on the Blackboard Editor.
Cite your source(s) as applicable.
For Questions (3.) through (6.):
Please review the GUI Programming Examples.
(I.) User-defined methods are required.
(II.) Parallel arrays are required. One array should be for the data variable and the other array should be for the
frequency.
(III.) You may use a pre-defined array (ListBox) or you may allow the user to enter the values (MultiLine TextBox)
(IV.) Desktop application is optional. You may develop a console application.
(V.) Multiple forms are optional.
(3.) Please review the Solved Examples on the Measures of Center
Find any question that has Ungrouped Data with frequency.
(a.) Write a program that computes the measures of center for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(4.) Please review the Solved Examples on the Measures of Spread
Find any question that has Ungrouped Data with frequency.
(a.) Write a program that computes the measures of dispersion for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(5.) Please review the Solved Examples on the Measures of Position
Find any question that has Ungrouped Data with frequency.
(a.) Write a program that computes the measures of location for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(6.) Please review the Solved Examples on Descriptive Statistics
Find any question that has Ungrouped Data with frequency.
(a.) Write a program that computes the measures of center and/or the measures of variability and/or the measures of position for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
vary, variable, data type, data value, value, container,
Students will:
(1.)
(2.)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(4.) Type C# Multidimensional Array and/or C# Jagged Array
in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(5.) Type C# Multidimensional Array and/or C# Jagged Array
in the search bar and view/read the results.
(1.)
(1.)
There are four options for your Final Exam
Please choose only one option.
This option is based on your textbook (MindTap course).
This implies that it is not free.
However, you have two-weeks free access.
So, it is free if you can complete all the graded assessments in two weeks.
Access the MindTap Course
Course Key: MTPP-7RJQ-1PVN (Did you notice it three times in this document?)
This exam is designed to assess your understanding of the beginning C# concepts.
You have reviewed several topics and several concepts in each topic for eight modules.
Pick at least $1$ concept in at least $1$ topic in each of the $8$ modules.
That gives at least $8$ concepts in $8$ different topics in $8$ modules.
Find two more concepts in any topic in any module.
That gives $10$ concepts.
For each concept, please:
(1.) Write at least three sentences about that concept.
(2.) Develop a program about that concept.
In other words, write at least one code example about the concept.
Run the code.
Display the output.
Deliverables:
(1.) 10 concepts in 10 different topics for $8$ modules
Please write the: Module number, the Topic, and the Concept
(2.) Three sentences for each concept.
(3.) Code for each concept.
(4.) Output for each concept.
Please submit all these information as a zipped folder (.zip only) in the Final Exam folder of the Blackboard course.
Candidates for this exam are seeking to prove core software development skills. It is recommended that candidates be
familiar with the concepts of and have hands-on experience with the technologies described here either by taking
relevant training courses or by working with tutorials and samples available on MSDN and in Microsoft Visual Studio.
Candidates are expected to have some experience with C# or Microsoft Visual Basic.NET
Please review some of the questions and answers of the
Microsoft Software Development Fundamentals Exam
(https://www.itexams.com/exam/98-361)
This is Free But Requires Patience
Focus on what we covered (Beginning C#).
However, you are welcome to review all of them and attempt only the C# topics.
Student: Mr. C, you are giving us a final exam with the answers?
How nice of you?
Teacher: Yes of course, I am nice. 😊
But, please read on.
First-come, first-served basis
A particular question may NOT be done by more than one student.
In other words, no two or more students are permitted to do the same question.
Please:
(1.) Pick any five questions.
(2.) Go to the Final Exam Questions forum of the Blackboard course.
(3.) Write the question numbers in that forum only if it has not been written by any other student.
In other words, you need to review any questions posted by your colleagues and make sure that you do not attempt
the same question.
(4.) Explain the solutions of those five questions using your own explanations
and your code examples.
(5.) Number the questions, the solutions, your code examples, and your
explanations based on the actual question numbers.
(6.) Submit the actual questions, the corresponding numbered solutions, your
corresponding numbered explanations and your corresponding code examples and any other relevant
information in the Final Exam folder of the Blackboard course.
(7.) Make your work easy for me to grade.
In other words, write detailed clear specific explanations.
Do not give me any avenue to deduct points.
(1.) Sample 1
There are three options for your Final Project.
Please choose only one option.
This option is based on your textbook (MindTap course).
This implies that it is not free.
However, you have two-weeks free access.
So, it is free if you can complete all the graded assessments in two weeks.
Access the MindTap Course
Course Key: MTPP-7RJQ-1PVN (Did you notice it three times in this document?)
It is important you communicate with me for approval prior to doing this project.
Because the course deals with only desktop applications and console applications,
(rather than web applications and mobile applications), you may not do any project that requires a web server
such as contact forms and registration forms among others.
The final project is designed to assess problem-solving skills using the knowledge you have acquired in the
course.
In that regard, solving at least a real-world problem using the knowledge gained in the course is expected.
(1.) Think about any of these companies: our Institution: Kent State University; your local campus; your work place; public and
private schools (excluding home schools); organizations, firms, and businesses
(excluding controversial firms and the like).
Any company you choose should have a verifiable website.
The direct link of the company's website is required.
(2.) Identify a problem on the website that you want to solve.
The problem must be solved by programming using the knowledge acquired from any of the course
topics/concepts/description/learning objectives.
Think about your Midterm Project. You solved a problem: calculating bills, federal taxes, etc.
(3.) Develop the computer program to solve the problem.
Test the program to ensure that it works.
Write detailed comments as applicable.
(4.) Prepare a Documentation Manual/Reflection for the project.
Please cite your sources accordingly.
What is the company?
What is their website?
What problem did you identify?
Did you solve the entire problem or part of the problem?
What course topics/concepts/description/learning objectives did you apply in solving the problem?
How did you solve the problem?
Did you encounter any issues while trying to solve the problem?
Are there any limitations to the project?
Are there any recommendations to the company?
Deliverables:
(1.) Program (all files)
(2.) Clear screenshots of your program (code and output)
(3.) Project Reflection/Documentation Manual
Please submit all these information as a zipped folder (.zip only) in the Final Project folder of the Blackboard course.
The final project is designed to assess your understanding and analysis of data using the knowledge you have
acquired in the course.
Please:
(1.) Visit my website on: Descriptive Statistics
(2.) Review the information for a good understanding of Descriptive Statistics.
It is highly likely that you have a prior knowledge of this topic. Is that right?
(3.) Click the Project link.
(4.) Review the Project Examples. Ensure you follow all the instructions and directions.
(5.) Complete the Final Project for your course.
(6.) Ask questions. I can help.
If you have any issue at any time and you have reviewed the resources I provided and you cannot fix the issue,
please attend the Office Hours/Live Sessions so I can help you.
(7.) Include all these: (documentation of all your Math work and the .exe file) in OneDrive, create a
shareable link, and post the link in the Final Project Drafts forum of the course on Blackboard or send to me via email.
You may also upload them directly if you prefer.
I shall review and provide feedback.
(8.) When you are done with your project:
Make sure your executable file runs by itself outside the project folder
If it does run, include these three items: single executable file (that runs by itself outside the folder), the
Math documentation (Word document that has the Math part), and the entire project folder, into a folder,
zip the folder (.zip extension only) and submit it in the appropriate area of the Blackboard course.
If it does not run, please fix it.
If you cannot fix it, please attend the Office Hours/Live Sessions so I can help you.
NOTE: Any actual project submitted to me via email will not be graded.
Advanced concepts of C# including classes and objects, inheritance, polymorphism, arrays, exception handling, files and streams and Extensible Application Markup Language (XAML). Prerequisite: IT 20021
By the end of this course, you should be able to do the following:
(1.) Explain Classes and Objects, Methods Data Types, Variables, Assignment, and Operators.
(2.) Demonstrate the use of control structures.
(3.) Utilize arrays and strings.
(4.) Utilize stream input and output, and file processing.
Students will:
(1.) Discuss the terms used in object-oriented programming.
(2.) Create a class.
(3.) Create a constructor.
(4.) Implement different constructors.
(5.) Overload constructors.
(6.) Create a destructor (destroy a constructor).
object-oriented programming, class, object, namespace, access modifier, public, private, protected, internal, protected internal, private protected, member access expression, field, attribute, property, assessor, method, function, constructor, parametized constructor, copy constructor, default constructor, static constructor, private constructor, overloading constructors, chaining constructors, this, keyword, concrete class, enum, enumeration
(1.) Textbook Chapter
(2.) Microsoft Tutorials: Learn C#: Free Tutorials and Videos
(https://dotnet.microsoft.com/learn/csharp)
(3.) Microsoft Tutorials: Classes and Objects
(https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/intro-to-csharp/introduction-to-classes)
(4.) Microsoft Tutorials: Classes
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes)
(5.) Tutlane Tutorials: Objects and Classes in C#:
(https://www.tutlane.com/tutorial/csharp/csharp-classes-and-objects-with-examples)
Classes and Objects to C# Destructor
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(6.) Type Object-oriented Programming in C# and/or OOP in C# in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(7.) Type Object-oriented Programming in C# and/or OOP in C# in the search bar and view/read the results.
System.Console.WriteLine("THANK GOD");System is the namespace Console is a class in that namespace
using System; Console.WriteLine("THANK GOD");So, the using keyword for the namespace, System eliminates the need for writing System.Console.WriteLine.
Class object = new();
ComputerScience student1 = new();
var object = new Class();
var student1 = new ComputerScience();
An Access modifier is a keyword used to declare the accessibility of a class member or
type.
It is used to control the visibility and security level of a class or class member.
The first name of a person can be made public. However, the person's SSN (social security number) should not be
made public.
A person's social security number should shoud of course, be made private.
Similarly, there are some class members that can be made public and there are some that should not be
made public.
In C#, we have six access modifiers.
They are:
Access Modifier | Accessibility Level |
---|---|
public | Access is not restricted. The class member can be assessed outside the class that it was created. |
private | Access is limited to the containing type. The class member can only be assessed within the class it was created. |
protected | Access is limited to the containing class or types derived from the containing
class. The class member can be assessed within the class it was created, or in a class that is inherited from the class that it was created. |
internal | Access is limited to the current assembly. |
protected internal | Access is limited to the current assembly or types derived from the containing class. |
private protected | Access is limited to the containing class or types derived from the containing class within the current assembly. |
NOTE:
(1.) If an access modifier is not specified for a class member, that class member is private by default.
(2.) Access modifiers are not used with namespaces. Namespaces are not actually classes or class
members. They are used to organize classes.
Student: What if students want to greet their fellow students?
Teacher: Good question.
This means that we need to expand our program.
As we add more requirements, the program starts getting large.
But, we do need to simplify the program.
So, let us begin by having separate files for this program.
Let us create another file for our class.
Let us name that file, ComputerScience.cs
So, we will have two files: ComputerScience.cs (that will contain our class) and Program.cs (that
contains the main class).
Keep in mind we already created this class.
We just want to put it in another file so it is separate from the main class.
Then, we can add as many members as we want.
The steps in creating the ComputerScience.cs class are:
In the Solution Explorer window (the window on the Right Hand Side) of the Visual Studio IDE:
(1.) Right-click the namaespace, Classes
(2.) Point your mouse on the Add menu
(3.) Click the Class submenu.
In other words, we want to add a class
We shall name that class, ComputerScience.cs
Please see the screenshots below.
Save All (Ctrl + Shift + S)
Build the solution.
Run the solution.
Whenever you make any change in either file; please ensure that you:
(1.) Save All then you
(2.) Build the solution. If the Build succeeded (as should be seen in the message on your computer),
then you
(3.) Run the solution.
If there were build errors, you should
review the line numbers where those errors occurred, as well the errors.
Fix the errors, build the solution again, and run the solution.
Notice that the two classes: the main class: Program.cs and the user-defined class: ComputerScience.cs
have the same namespace: Classes
Remember that we created the user-defined class by right-clicking the namespace: Classes in the Solution Explorer and
adding the class: ComputerScience.cs
Back to your question:
We want students to greet themselves.
We already know that Chukwuemeka is the teacher and Samuel is the student.
Let's say we want another student, Dominic.
The teacher would greet the two students, Samuel and Dominic.
Each student will greet the other as well.
In other words:
Chukwuemeka will greet Samuel
Chukwuemeka will greet Dominic
Samuel will greet Dominic
Dominic will greet Samuel
So, we have four greetings of "Welcome to our Programming class!"
Example 6: Greetings among the teacher and two students.
Student: What if we have different names for the teachers and students?
Do we need to keep defining each name as a field when we have a new teacher and new students?
Teacher: Good question.
More functionalities means that we should find a way of achieving the same output with less code.
This leads to...
What we can do to address your question is to create a constructor.
A constructor in C# is a special method that:
has the same name as the class; used to initialize objects; and
does not return values.
Hence, whenever we create an object (the instance of the class), the constructor is called.
The constructor is a method. So, it needs to have an access modifier.
Note that it should have the same name as the class name.
So, you can say that is a special method because it has an access modifier, has the same name as the
class name, may or may not have parameters that would be defined as initial variables or values of the class
members, and does not return any value.
There is always at least one constructor in every class.
If a class is created without a constructor, the compiler creates a default constructor for that class.
C# constructors are:
(1.) Default Constructor
(2.) Parametized Constructor
(3.) Copy Constructor
(4.) Static Constructor
(5.) Private Constructor
access modifier ClassName() { statement; }Let us implement a default constructor
access modifier ClassName(parameter1, parameter2, ...) { statement; }We shall use parametized constructors frequently in the course.
We can overload constructors.
This implies that we can create two or more constructors with the same name but different parameters.
NOTE: This is based on what I have found out.
To overload two or more parametized constructors:
(1.) If you use the same parameter data type and the same number of parameters for one constructor, do
not use that same parameter data type and number of parameters for the other constructor (overloaded constructor).
For example: If you use the string data type for three parameters in the first constructor, do not use the
string data type and three parameters for the other constructor.
You may use the string and integer data types for three parameters for both constructors (because they are different
data types).
In addition, you may use the string data type and three parameters for the first constructor, and the string data
type but two parameters for the second constructor (because the number of parameters are different).
(2.) The number of parameters in the constructors must not be the same.
Let us overload a parametized constructor with another parametized constructor.
Teacher: Did you notice the functionality of overloaded constructors?
We can change the parameters with ease.
We can write a short story/poem/drama about KSU among others.
Student: What if we wanted the parameter data type and the number of parameters in both
constructors to be the same?
Can we do that?
Teacher: What do you think?
Student: I don't know. That's why I asked.
Teacher: Yes, we can.
But, one of constructors would be a default constructor and the other constructor would be a
parametized constructor.
The default constructor would have fields (with the same data type), rather than parameters.
The parametized constructor would have parameters with the same data type as the fields in the default
constructor.
Let's do it.
Let us overload a default constructor with a parametized constructor.
Teacher: Do you know something else we can do besides overloading a default constructor and a parametized
constructor?
Student: No Sir.
Teacher: Assume we have the same parameter data type that would perform the same function, we can use a
Copy constructor.
Let's say we have two teachers, two students, and two courses.
The two different teachers will greet the two different students enrolled in two different courses.
Both perform the same task, greeting even though they are different entities of the same data
type.
Rather than overloading a default constructor and a parametized constructor, we can
create a parametized constructor and copy that parametized constructor.
Let's see how it works.
// Parametized constructor access modifier ClassName(parameter1, parameter2, ...) { statement; } // Copy constructor access modifier ClassName(ClassName newObjectName) { statement; }Let us copy a constructor
static ClassName() { statement; }Let us implement a static and a default constructor to show that a static constructor is called only one time
Whenever a constructor is declared, if the access modifier is not specified; by default, that constructor is
private.
A private constructor can only be declared by specifying the access modifier of the constructor as
private.
We shall skip this section for now.
We shall focus on creating private fields in the class and accessing those fields using properties. Properties is
covered in the next module.
Constructor Chaining is the process of calling a constructor from another constructor.
It involves several overloaded constructors.
...
A destructor is a special method used only in a class to destroy an object and
clean-up when the object is collected by the garbage collector.
It is also known as a finalizer
A destructor:
(1.) is preceeded with a tilde sign before the constructor.
For example: if the constructor is ComputerScience, the destructor is ~ComputerScience
(2.) can only be one in a class.
A class can have only one destructor.
(3.) cannot be inherited or overloaded.
(4.) cannot be called. It is invoked automatically.
(5.) does not take modifiers.
(6.) does not have parameters.
We shall discuss destructors in details when we discuss garbage collection.
(1.) Write a program for a scenario/case/example where you would:
(I.) Implement any of the constructors (besides the static and private constructors) that we discussed.
(II.) Use a combination of at least two different data types for the class fields.
This implies that you should have at least two class fields of different data types.
(2.) Write a program that overloads at least two (two or more) constructors.
(3.) Write a program that chains at least three (three or more) constructors.
(1.) Write a different constructor that will give the same output as the constructor used in the initial post.
(2.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(1.) Develop a desktop application that has three buttons.
One button named Constructor should implement any of the constructors (besides the static and private constructors)
that we discussed.
Use a combination of at least two different data types for the class fields.
This implies that you should have at least two class fields of different data types.
Another button named Overload Constructor should implement the overloading of at least two (two or more) constructors.
The third button named Chain Constructor should implement the chaining of least three (three or more) constructors.
Students will:
(1.) Discuss the properties of a class
(2.) Implement the various properties in a class.
(3.) Develop a console application that implements classes, objects, constructors, and properties.
(4.) Develop a desktop application that implements classes, objects, constructors, and properties.
get, get accessor, getter, set, set accessor, setter, void, parametized constructor, auto-implemented property, expression-bodied definition property, exceptions, throw an exception, encapsulation, reference, dependency, event, event handler, backing store, solution, container, event, event handler, tuple, trigger, behavior
(1.) Textbook Chapter
(2.) Microsoft Tutorials: Learn C#: Free Tutorials and Videos
(https://dotnet.microsoft.com/learn/csharp)
(3.) Microsoft Tutorials: Using Properties
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties)
(4.) Microsoft Tutorials: Properties
(https://docs.microsoft.com/en-us/dotnet/csharp/properties)
(5.) Tutlane Tutorials: C# Properties
(https://www.tutlane.com/tutorial/csharp/csharp-properties-get-set)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(6.) Type Object-oriented Programming in C# and/or OOP in C# in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(7.) Type Object-oriented Programming in C# and/or OOP in C# in the search bar and view/read the results.
access modifier data type property name
Please review the BMI information on these two government websites [from the Center for Disease Control and Prevention (CDC) and the National Heart, Lung, and Blood Institute of the National Institutes of Health (NIH)]
About Adult BMI | Healthy Weight, Nutrition, and Physical Activity | CDC
(https://www.cdc.gov/healthyweight/assessing/bmi/adult_bmi/index.html)
and
Calculate Your BMI - Standard BMI Calculator
(https://www.nhlbi.nih.gov/health/educational/lose_wt/BMI/bmicalc.htm)
As at today, the 3rd day of September, 2020; the BMI information on both websites are:
NIH website
Calculate Your BMI - Standard BMI Calculator
CDC website
About Adult BMI | Healthy Weight, Nutrition, and Physical Activity | CDC
$ BMI = \left(\dfrac{weight}{height * height}\right) * 703 \\[5ex] weight\:\:is\:\:in\:\:pounds (lb) \\[3ex] height\:\:is\:\:in\:\:inches (in) $
$
BMI = \left(\dfrac{weight}{height * height}\right) \\[5ex]
weight\:\:is\:\:in\:\:kilograms (kg) \\[3ex]
height\:\:is\:\:in\:\:meters (m) \\[3ex]
$
If you need help with conversion of units, please review the Tables and Examples in
Measurements and Units
Teacher: What do you notice in both websites?
Student: They both have the information on the BMI.
In addition, the CDC website has information for both Adult BMI and Child & Teen BMI among others.
The NIH website has recommendations among others.
Teacher: That is correct. What else?
Student: They have the BMI calculator.
Teacher: Did you notice any difference in the calculator on both websites?
Student: The NIH website has BMI calculator for both Standard and Metric versions.
The CDC website has the BMI calculator for only the Metric version.
Teacher: Did you notice any issue/concern about the BMI information?
Student: Not really. Why?
Teacher: So, this is what we are going to do.
Let us develop the BMI calculator.
That calculator will calculate the BMI.
Then, we shall interpret that BMI, and make a recommendation.
.
The CDC website gave us the formula for calculating the BMI. So, we shall use it.
As you can see, our calculator would have to use conditional statements for the interpretation and recommendation.
But, here is the issue.
Student: Wait, I think I see the issue.
The issue is with the domains.
Teacher: Correct!
Anyone having a BMI between $18.5$ and $24.9$ both endpoints included has a Normal weight.
This is: Normal weight: [18.5, 24.9]. It is a closed interval (relate with Mathematics).
So, the Overweight range for the BMI should be the weight greater than $24.9$, (rather than beginning from $25$) and ending at $29.9$
For the Overweight range, the first endpoint is not included, but the second endpoint is included.
This is: Overweight: (24.9, 29.9]. It is a half-open half-closed interval (relate with Mathematics)
Teacher: Do you know why this would be a problem if the programmer does not fix these issues before developing the calculator?
Student: Yes. Because there would not be any interpretation for anyone whose BMI is between $24.9$ and $25$
But, I do see that the BMI information is for values rounded to one decimal place.
Teacher: That is correct.
And we shall develop our calculator to round to one decimal place.
But, it is important we fix the issues.
What if we do not want to round?
Look at the two examples on the CDC website. The BMI values were rounded to two decimal places.
If we developed our calculator to round to two decimal places with the information on those websites "as is"; then we would not have the interpretation and recommendation for those two examples ($24.98$ and $24.96$) because those values are greater than $24.9$ but less than $25$.
Student: That makes sense.
So, the last one: Obese should be BMI greater than $29.9$, rather than greater than $30$?
Teacher: That is correct.
So far, we discussed:
(1.) Methods (Functions) in C# Programming
(2.) Introduction to Object-oriented Programming (Classes, Constructors, and Objects) in Module 1.
(3.) Properties in this module: Module 2.
Let us apply what we learned so far.
We shall develop a console application and a desktop application for the Body Mass Index (BMI) calculator.
(1.) The program should accept user inputs of:
(I.) First name
(II.) Last name
(III.) Weight
(IV. Height
(2.) The program should output the:
(A.) BMI value
(B.) Interpretation
(C.) Recommendation
(3.) The program should address user-input errors of non-positive numbers for the weight and the height.
Inform the user.
Then, exit the program without causing it to crash.
(1.) We shall create a new project: Module2
The project name is the namespace: Module2
The main class file will be named Program.cs
(2.) Because the first name and the last name is not needed in the calculation, we shall ask for the user input of
first name and last name in the Main method
(3.) We shall create a class under the project.
I prefer creating a class by adding a class (as a separate file) rather than creating the class inside the
Program.cs.
I like to separate classes. However, do what you prefer.
So, we shall add a class and name the class, BodyMassIndex.cs
Please note that the class should be under that project/namespace: Module2
Teacher: You know something I learned in America...as regards dating?
Student: What is it?
Teacher: You should not ask a woman her weight.
Student: LOL. Is that all you learned?
Teacher: Another thing is that you should not ask a woman her age.
But, a woman can ask a man his age.
Student: That is correct. In America, you do not ask a woman her weight or her age.
Teacher: Is that not double standard?
Anyway...B2B (back to business)
(4.) We shall create two fields: weight and height for our class: BodyMassIndex.cs
Because we shall associate the weight and height with the user's first name and last name, we shall declare
these fields as private.
Be reminded that even if you do not specify an access modifier for the fields, they are declared as private by default.
However, it is good practice to specify access modifiers.
(5.) We shall create public properties for these private fields so we can access them.
Remember that method names in C# should begin with uppercase letter.
Property is a special method.
So, the properties should be the uppercase beginning letters of the fields.
(6.) We shall create a parametized constructor that will initialize the class fields.
Assign the fields to the constructor parameters.
(7.) We shall create a method: BodyMassIndexDetails
This method is necessary to calculate the BMI.
We need to throw an exception to ensure that only positive values are entered for the user input weight and
height.
Zero and negative values should not be allowed.
No worries. We shall disuss Exception Handling in details in another module. For now, please learn how to
do it in this application.
In addition, we shall interpret the BMI and make recommendation based on the calculated BMI value.
We shall create three more variables here. These variables are local variables.
For local variables that is directly calculated from the class fields, we do not need to initialize.
However, for local variables that are not directly calculated from the class fields, we
must initialize those variables.
(8.) Go to the Main method in the Program.cs class and ask for user input of the first name, last
name, weight, and height
NOTE:
We will declare variables for: first name, last name, weight, and height in the Main method.
However, we shall use the constructor parameters as the same variables for weight and height
In other words: our constructor parameters are: weightPounds and heightInches
We shall use that weightPounds and heightInches as our variables.
Also: we shall use that weightPounds and heightInches as the arguments when we create the
object.
Recap:
We shall use weightPounds and heightInches and their data types as the parameters for the constructor in our BodyMassIndex class.
We shall use the same weightPounds and heightInches and their data types when we declare variables in the Main method.
We shall still use the same weightPounds and heightInches (without the data types) as our arguments in our object.
Create the object: calculateBMI
Display your summary and make it look nice.
To underline anything in the console window:
\x1B[4m is the code to underline.
\x1B[0m is the code to end the underline (reset).
Use the object to call the method.
(9.) Test your program for each piece/case.
In other words, test your program to ensure that the calculation, interpretation, and recommendation is correct for
all the BMI options.
You may also test the examples on the CDC website.
(10.) Test your program to check for user input errors.
In other words, test your program for exception handling.
Stop Debugging after taking the screenshot.
Please see the images.
Review the comments.
Results:
Exception Handling:
(1.) We shall create a class library named BMIClassLibrary.
A class library is a library of predefined classes and/or user-defined classes that
programmers can use and reuse to develop applications.
The class library does not run on it's own. It is not a standalone application. It is being used/resued to develop
applications. These applications could be console applications, desktop applications, web applications, or mobile
applications.
Student: Why not just use the class we created already?
Why create a class library?
Teacher: The application we just did was a Console Application (works in the console window of any
desktop/laptop computer; the executable file, .exe file can be made to run in the console window of any
computer)
The application we want to do is a Desktop Application (works in any desktop; the executable file,
.exe file can be made to run in desktop/laptop computer)
Both applications have different interfaces even though they have the same functionality.
So, we shall make some changes to our code logic for the desktop application.
The main reasons for using a class library rather than a class are:
(A.) The development of desktop, web, mobile applications for the .NET framweork
We can use the same class library to develop desktop, web, and mobile applications for the Windows platform.
(B.) Reusability. We can use the same class library for any project we want to develop.
Some may argue that a class is resuable. However, a class library contains at least a class (one or more classes).
Besides, imagine creating many classes for many projects as opposed to creating a single class library for those
projects.
Please see the step-by-step directions in the images.
We will change the location for the library. It is my preference. I like to have quick access to my projects.
Usually, I would not change the Solution name.
As noted by the definition, a solution is a container for one or more projects in Visual Studio.
At the moment, the Solution name is the same name as the Class Library name. However; because I might reuse this
class library for another project, or add more classes to this library for other projects, (and please consider
these factors when creating your library); I shall rename the Solution name.
So, we will uncheck the box, and rename the Solution name to Module2Library
You have the option to keep the Solution name as the Class Library name/ Project name (without unchecking the box);
or rename it (by unchecking the box).
As you can see, that Class1.cs is just a simple class. It does not have all the libraries that we need.
So, we have to delete it, and add a new class under the BMIClassLibrary.
We shall name that class the same name we used for the class we created in the Console Application.
So, we shall name the class: BodyMassIndex.cs
As you can see, the BodyMassIndex.cs has more libraries than the default Class1.cs
Next, we are going to copy our entire code under the BodyMassIndex.cs in the Console
Application and paste it in the BodyMassIndex.cs in the Class Library
We will not copy any code from the Program.cs (Do you now see one of the reasons why it is good to
separate your created class: BodyMassIndex.cs from the System class: Program.cs)
We shall make changes to the code we copied.
(2.) We shall declare the class: BodyMassIndex.cs as public (as we did in the Console Application) because we
are going to use the class.
(3.) We shall create the two fields: firstName and lastName. Remember they were not included in what
we copied. So, we need to include them.
The first name and last name of a person is usually a public information.
We shall declare them as public so we can access them outside the class.
(4.) We shall add two parameters: fName and lName, and assign those two class fields: firstName
and lastName to the them (Initialize the class fields similar to what we did in the Console Application).
(5.) In the Console Application, we used the void method
Well, we cannot use the void method here.
Reason: The void method does not return values. But, we want the MessageBox to display our values.
The MessageBox returns string data type. So, the issue is that C# will not convert void data type to a string data
type. This will not work.
If we decide to use string method (method that returns only a string data type), it will not work because the BMI is
of double data type.
If we decide to use double method (method that returns only double data type), what about the first name, last
names, interpretation of the BMI, recommendation that are strings?
If we decide to use multiple methods that return different data types, then we are making this project
cumbersome...sort of killing a fly with a hammer
So, what data structure can we use that will return different data types?
You probably covered this in the Beginners course: the Tuple data structure.
So, we are going to use a method that returns the elements of a tuple.
Our tuple shall consist of the double data type for the BMI, the string data type for the interpretBMI, and the
string data type for the adviceBMI.
The method is named: BodyMassIndexDetails()
Please review the code logic in the images and review the comments.
(6.) We shall append each output in a new line
The output includes: first name, last name, weight, height, BMI, interpretation, and recommendation.
Because we want to append each output in a new line, we shall be using the StringBuilder class with the
AppendLine method
This is the documentation for the StringBuilder.AppendLine Method: include the link
(https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendline?view=netcore-3.1)
So, we shall delete the Console.WriteLine() method and use the sb.AppendLine() method
(7.) We shall override the ToString() method
This is necessary for:
(A.) Nice/Formatted display of our output.
(B.) Keeping all our results in one method.
(C.) Returning a string that represents our object so it can be displayed in the any of the Toolbox tools that we
use.
This is the documentation for the ToString() Method: include the link
(https://docs.microsoft.com/en-us/dotnet/api/system.object.tostring?view=netcore-3.1)
Call the method: BodyMassIndexDetails()
Create variables with the same names as the elements
Create an object of the StringBuilder() class.
Assess these variables(tuple elements) and use them in the StringBuilder() class
Return the object with the ToString() method.
(8.) Next, we have to create the desktop application.
For this module, we shall create the Windows Form App (.NET Framework)
In a later module, we shall use the Windows Presentation Foundation (WPF)
The WPF App (.NET Framework) uses Extensible Markup Language (XAML) to create the interface; and the
application developed with it can be published in the Windows Store.
But, let us stick with Windows Form App (.NET Framework) for this desktop application.
At the moment, the BMIClassLibrary is the Startup Project (indicated by the bold emphasis).
Build it. Then, try to run it.
The Build succeeded. But, the project did not run.
Remember, as mentioned earlier; the class library is not a standalone application. It will not run on it's own.
The main thing is that the Build succeeded
In the Solution Explorer window,
We have to add a New Project under the Solution name: Module2Library
The new project will be a Windows Form Application for C#
We shall name it: BMICalculator
Then, we will set it as the Startup Project (indicated by the bold emphasis).
(9.) Go to the Properties window
Change the Text property of the form from Form1.cs to BodyMassIndexApplication.cs and presse
the ENTER key on your keyboard.
Leave the (Name) property of the form: Form1 as is Do not mess with it.
Change only the Text property.
Save All changes (Ctrl + Shift + S)
(10.) Go to the Solution Explorer window;
Under the BMICalculator Project, add the BMIClassLibrary as a reference.
So, add that BMIClassLibrary under References
(11.) Verify that the BMIClassLibrary has been added under References because we shall use that
library.
We need the Toolbox to set up the user interface
So, go to the View menubar and click the Toolbox item.
(12.) Auto Hide the Toolbox
Expand the All Windows Forms
Adjust each window: Toolbox window, Design window, Solution Explorer window, and
Properties window as necessary.
Let us begin to design the user interface
We need:
Four labels: First Name, Last Name, Weight, and Height
Four TextBoxes to capture the user input of those fields
Three buttons: the CalculateBMI button, the Reset button because we need to clear the fields by
resetting it before we test each condition (like we did in the Console Application), and the Close button to
close the application.
One MessageBox to display the output.
List the Properties in Alphabetical order by clicking the Alphabetical icon in order to make them easy to find.
Change the Font property of every toolbox: label, TextBox, button to Times New Roman Regular 16
Set the width of each TextBox to 150.
Change the TextAlign property to Center
Center the buttons horizonatally (Select them: Format --> Center in Form --> Horizontally)
Do the same for each label and the corresponding TextBox
Under the Properties window:
Change the:
Text property of label1 to First Name and the (Name) property of label1 to
firstName
Text property of label2 to Last Name and the (Name) property of label2 to
lastName
Text property of label3 to Weight and the (Name) property of label3 to
weight
Text property of label4 to Height and the (Name) property of label4 to
height
Text property of button1 to Calculate BMI and the (Name) property of button1 to
calculateBMI
Text property of button2 to Reset and the (Name) property of button2 to
reset
Text property of button3 to Exit and the (Name) property of button3 to
exit
Change the Name property of:
TextBox1 to txtBoxFirstName
TextBox2 to txtBoxLastName
TextBox3 to txtBoxWeight
TextBox4 to txtBoxHeight
Save All
Build Solution
Run the project by clicking the Start icon
Click the Stop Debugging (Shift + F5) icon to stop.
(13.) Now, onto the code logic
Let us add functionality to this form.
Double-click the Calculate BMI button to open the Code window
This is necessary so we determine what should happen when a user clicks the button.
Scroll all the way to the top
Add this command to the System: using BMIClassLibrary
This is necessary because we want to use that class library.
Scroll down
In the event handler for the Calculate BMI button: calculateBMI_Click(object sender, EventArgs
e)
Create the variables for the fields. Use the same name as the constructor parameters.
Create the object: computeBMI which is an instance of the class: BodyMassIndex
Handle Exceptions (Exception Handling) for the weight and the height. This is necessary to to check for user input
errors. It is also helpful to prevent a system crash of our program due to user input errors.
Display the output in a MessageBox
Please review the images.
Please review the comments.
(14.) We now head over to the event handler for the Reset button: reset_Click(object sender, EventArgs
e)
and the event handler for the Exit button: exit_Click(object sender, EventArgs e)
Please review the images.
Please review the comments.
Class Library: BMIClassLibrary
File: BodyMassIndex.cs
Design Window: Form1.cs[Design]
Code Window: Form1.cs
(15.) Test your program for each piece/case.
In other words, test your program to ensure that the calculation, interpretation, and recommendation is correct for
all the BMI options.
You may also test the examples on the CDC website.
Output for Different Pieces/Cases/Conditions
(16.) Test your program to check for user input errors.
In other words, test your program for the exception handling.
Stop Debugging after taking the screenshot.
Please see the images.
Review the comments.
Exception Handling
Student: The MessageBox is tiny
Can we use another toolbox to increase the output?
Teacher: Sure.
Student: Also, you did not include the unit for the weight and height.
This is the kind of thing you take off points for.
Teacher: You are very correct.
Thank you for pointing it out.
Including the units is very important.
Let us add two labels...well actually we can just copy and paste the Weight label two times
Then, we shall change the Text property of one of the labels to pounds for the unit of the Weight
and change the Name property of that label to lblPounds
Similarly, we shall change the Text property of the other label to inches for the unit of the Height
and change the Name property to lblInches
For the appearance and size, let us use a RichTextBox
Just drag it from the Toolbox and drop it in the form
Change the Font property to Times New Roman Regular 16 like we did the rest of the objects
Adjust the objects to fit in the form.
We shall name it: richTextboxOutput
Then, we shall make a minor changes in Form.cs
We shall modify the codes in Lines #55 and #56 and add Line #66
Then, Build the Solution.
And run it.
Using a RichTextBox instead of a MesssageBox to Display the Output
For Questions (1.) and (2.)
(I.) Consider any concept/scenario that uses conditional statements.
Use at least two (two or more) different conditions.
The BMI Calculator has four different conditions.
But, please use any application that has at least two different conditions.
(II.) Accept user input(s).
(III.) Use a class you created.
(IV.) Use at least one private field.
(V.) Use properties that should access that private field.
(VI.) Use at least one method.
(VII.) Include some checks for user input errors.
(VIII.) Test your program and display the result/output for each condition.
(IX.) Test your program for user-input errors.
(X.) Submit all the screenshots in your DB 2 forum on Blackboard.
(1.) Develop a console application for your concept.
(2.) Develop a desktop application for your concept.
(1.) If your colleague developed only a console application, develop the desktop application for that concept.
(2.) If your colleague developed only a desktop application, develop the console application for that concept.
(3.) If your colleague did not use a constructor, develop the same application using a constructor.
(4.) Other substantive responses.
For Question (1.)
(I.) Consider any concept/scenario that uses conditional statements.
Use at least two (two or more) different conditions.
The BMI Calculator has four different conditions.
But, please use any application that has at least two different conditions.
(II.) Accept user input(s).
(III.) Use a class you created.
(IV.) Use at least one private field.
(V.) Use properties that should access that private field.
(VI.) Use at least one method.
(VII.) Include some checks for user input errors.
(VIII.) Test your program and display the result/output for each condition.
(IX.) Test your program for user-input errors.
(X.) Submit all the screenshots in your DB 2 forum on Blackboard.
(1.) Develop a console application and a desktop application for your concept.
One application will count for DB Post.
The other application will count for DB Response.
Please specify which one should count for DB Post and DB Response.
(2.) Develop a console application for an extension of my concept (the BMI application).
I did the application for the United States System (Customary System).
Extend the application by developing the calculator for the International System (Metric System).
The formula is on the screenshot.
Ask the user which system he/she wants to use to calculate the BMI.
Based on the user's selection, display the appropriate units for the weight and the height, as well as the output.
Test all the conditions for both systems.
(3.) Develop a desktop application for an extension of my concept (the BMI application).
I did the application for the United States System (Customary System).
Extend the application by developing the calculator for the International System (Metric System).
The formula is on the screenshot.
Ask the user which system he/she wants to use to calculate the BMI.
Your desktop application should have the dropdown list for both systems, but should be null be default (using a ComboBox)
Alternatively, you may choose to use Radio Buttons.
Based on the user's selection, display the appropriate units for the weight and the height, as well as the output.
Test all the conditions for both systems.
(1.) Textbook Chapter
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(2.) Type C# Exception and/or C# Exception Handling in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(3.) Type C# Exception and/or C# Exception Handling in the search bar and view/read the results.
exception,
Students will:
(1.) Handle exceptions in C#
(2.) Complete the Midterm Project on Piecewise Functions.
Please:
(1.) Visit my website on: Piecewise Functions
(2.) Read the Story to understand the idea of Piecewise functions.
(3.) Read the Overview of Piecewise Functions for more understanding of Piecewise functions.
(4.) Study the Applications of Piecewise Functions
(5.) Review the Project Examples. Ensure you follow all the instructions and directions.
(6.) Review the Midterm Project rubric for your course.
(7.) Complete the Midterm Project for your course.
(8.) Ask questions. I can help.
If you have any issue at any time and you have reviewed the resources I provided and you cannot fix the issue,
please attend the Office Hours/Live Sessions so I can help you.
(9.) Include all these: (documentation of all your Math work and the .exe file) in OneDrive, create a
shareable link, and post the link in the Midterm Project Drafts forum of the course on Blackboard or send to me via email.
You may also upload them directly if you prefer.
I shall review and provide feedback.
(10.) When you are done with your project:
Make sure your executable file runs by itself outside the project folder
If it does run, include these three items: single executable file (that runs by itself outside the folder), the
Math documentation (Word document that has the Math part), and the entire project folder, into a folder,
zip the folder (.zip extension only) and submit it in the appropriate area of the Blackboard course.
If it does not run, please fix it.
If you cannot fix it, please attend the Office Hours/Live Sessions so I can help you.
NOTE: Any actual project submitted to me via email will not be graded.
If you wish to save some time for research:
Please review the Piecewise Function projects done by my previous students.
The direct link of the verifiable websites are included.
(I.) VB Projects
(II.) C# Projects
(III.) C++ Projects
(IV.) Java Projects
You may not do any same application done by any of my previous students for Advanced C#
You may do any Piecewise Function application not done by any of my previous students for Advanced C#.
If you are not sure what project you may or may not do, please contact me via the school email.
inherit, inheritance, behavior, data, class members, colon :, parent class, base class, superclass, child class, derived class, extended class, subclass, ancestors, single inheritance, multilevel inheritance, transitive inheritance, sealed keyword, virtual keyword, override keyword, abstraction, abstract class, abstract method, interface, polymorphism, delegates
Students will:
(1.) Discuss the inheritance of a class.
(2.) Discuss polymorphism in object-oriented programming.
(3.) Write programs that demonstrate the inheritance of a class.
(4.) Write programs that demonstrate polymorphism.
(1.) Textbook Chapter
(2.) Tutorials by Microsoft:
Inheritance: Part 1
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/inheritance)
and
Inheritance: Part 2
(https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/inheritance)
(3.) Tutorials by Microsoft: Abstract and Sealed Classes and Class Members
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/abstract-and-sealed-classes-and-class-members)
(4.) Tutorials by Microsoft: Interfaces
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/)
(5.) Tutorials by Microsoft: Polymorphism
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/polymorphism)
(6.) Tutorials by Tutlane: Inheritance
(https://www.tutlane.com/tutorial/csharp/csharp-inheritance)
(7.) Tutorials by Microsoft: Delegates
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/)
(8.) Tutorials by Tutorialspoint: Polymorphism
(https://www.tutorialspoint.com/csharp/csharp_polymorphism.htm)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(9.) Type C# Inheritance and Polymorphism in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(10.) Type C# Inheritance and Polymorphism in the search bar and view/read the results.
There are three primary characteristics/pillars of object-oriented programming:
(1.) Encapsulation
(2.) Inheritance
(3.) Polymorphism
A teacher, Mr. C with his three students: Student $1$, Student $2$, and Student $3$
The students are dual enrolled high school students.
They are bold and smart.
They are taking a Computer Science course with Mr. C
Teacher: Today, we shall be discussing Inheritance
Student $1$: Is this a Biology class?
Teacher: Why do you ask?
Student $2$: Why do you answer questions with questions?
Teacher: Typical of Nigerians 😊
It saves you from getting into trouble.
Student $1$: I asked because we are studying Genetics.
Teacher: Interesting.
So, we can use some interdisciplinary knowledge from both courses.
My first question is:
What did you inherit from your parents: Dad, Mom, Grand Dad, Grand Mom (Father's side), Grand Dad, Grand Mom
(Mother's side), several generations on both sides, atavism?
Student $2$: What do you mean by atavism
Student $3$: It's a reappearance of an ancestral trait.
For example: Remember those Nigerian parents (both of them are Black) that gave birth to a white baby girl?
One of the reasons the doctors gave was dormant white genes which entered both of the female's parents' families
long ago.
That is atavism.
You can read the story online. Wait: here is the link from CBS News:
(https://www.cbsnews.com/news/white-baby-shocks-black-parents-medically-possible/)
Student $1$: CBS News? LOL
Teacher: Hey, do not say what you want to say.
This is not politics.
Student $1$: And what if I do?
Student $3$: Some other news sources have it as well.
Teacher: Okay guys, you have not answered my question.
Student $2$: Well, as you can see: I have blonde hair and blue eyes.
But surprisingly, my parents have brown hair and brown eyes.
Why is that?
Student $1$: Your parents have the dominant brown hair and brown eyes genes and the recessive blond hair
and blue eyes genes.
They passed those recessive genes to you.
Student $2$: Interesting.
But, if I want my children to have those dominant brown hair and brown eyes genes, what should I do?
Student $1$: Let me just invite you to our Biology course so you ask those questions.
I am still learning.
But, just pray for it. Do not do anything to try to disrupt nature.
Teacher: Okay, get back on track to my questions.
Student $3$: I inherited intelligence from my parents.
Student $1$: So, we had this argument in class: Is intelligence acquired or inherited?
Is it by nature or nature or both?
Teacher: Intelligence is both nature and nurture though it is more of nurture.
Student $1$: What are your reasons, Sir?
Teacher: You have two Nigerian parents, did not attend school did not have any formal education; yet
their children are the best graduating medical students.
Student $1$: Well, the fact that they did not attend school does not mean that they are not intelligent.
Someone who is not literate can still be intelligent. I think intelligence is wisdom.
Student $3$: I inherited tallness from my Mom.
My Mom is tall and my Dad is of average height.
Teacher: I am still waiting for your answer.
Student $1$: Who? Me?
Teacher: Yes of course.
Student $1$: I think I inherited my temperament from my Dad.
Teacher: Bold. Reactive (not proactive). High activity level. Persistent.
Student $1$: You got it.
But, you do know environmental factors contribute as well.
Teacher: Yes I know.
Just like Intelligence, Temperament is both nature and nurture. However, it is more of nurture.
Student $1$: Now, back to you, Mr. C
What did you inherit from your parents?
Teacher: Oh come on.
Can't you see it?
Everyone is looking at me.
Student $1$: Meaning?
That I am a very handsome man.
Everyone starts smiling/laughing
It's good to laugh and be relaxed before we start learning some codes.
Student $1$: We are looking at you because you are the professor.
Teacher: And because I am very handsome.
Alright, B2B...
Everyone says: Back to Business
So as you can see (based on our discussion), one can inherit traits from the Dad, Mom, Mom and Dad, grandparents, or
even ancestral traits.
So far:
In your previous course: the Beginner's course; we discussed
(1.) Method/Function
In the previous modules for this course, we discussed:
(1.) A class
(2.) Constructor
(3.) Property
Say that we created a class: Class $A$ with some members: fields, properties, and methods
We want to create another class: Class $B$ and use the members from class $A$ and also use additional members
Keep in mind that class members includes fields, properties, and methods.
Rather than create Class $B$ and define all those members from Class $A$, we can create Class $B$ as a child of
Class $A$ so that it inherits the class members from Class $A$ and then create the additional members for it.
We can also create Class $C$ to inherit some of the properties of Class $A$ and also some of the properties
of Class $B$
So, you can see it this way:
Class $A$ as the parent
Class $B$ as the child
Class $C$ as the grandchild
Remember one inherits the genes of grandparents and great grand parents and so on and so forth. The amount
depends on the percentage or fraction. (which you discuss in Genetics).
Welcome to Inheritance.
Inheritance is the ability of a class to inherit the members of
another class.
The class whose members are inherited from another class is known as the base class or
parent class or superclass
The class that inherits the class members from another class is known as the derived class or
child class or extended class or subclass
So, this is seen as:
Base class and Derived class OR
Base class and Extended class OR
Parent class and Child class OR
Superclass and Subclass (Compare to Superset and Subset in Algebra)
(Please get used to these words because we shall be using them interchangeably.)
Superclass and Subclass are preferred terms for the Java programming language.
The main purpose of inheritance is to reuse, extend, and modify the class members of a parent class by
the child class.
It allows one to define a child class that reuses (inherits), extends, or modifies/overrides the behavior of a parent class.
When a class is derived from a base class, the derived class implicitly gains all the members of the base
class, besides its constructors and finalizers.
The derived class reuses the code in the base class without having to reimplement it.
You can add more members in the derived class.
The derived class extends the functionality of the base class.
The ancestors of a derived class are the superclasses from which the subclass is derived.
public class DerivedClass : BaseClass(2.) C# supports only a single inheritance of the base class.
Let us discuss some advantages of Inheritance.
(1.) Code Reusability: As seen in the previous examples, we reused the class fields of the base class.
Inheritance is like the DRY (Don't Repeat Yourself) of programming because some class members of the base
class are reused.
Reusability leads to reduced development and maintenance costs.
(2.) Code Extensibility: Inheritance allows for modification and extension of code.
As seen in the previous examples, we modified and extended the fields that was inherited from the base
class, in the derived class.
(3.) Creation of Class Libraries: Inheritance facilitates the creation of class libraries.
(4.) Access to protected class members of the base class:
So far, we have:
(a.) Used the public access specifier.
(b.) Used the private access specifier.
Recall that we had to use Property to access a private class field.
But, what about the other access specifier: protected. We have not used it.
We shall use it in this module.
Recall that in the: protected access specifier: Access is limited to the containing class or types
derived from the containing class.
The class member can be assessed within the class it was created, or in a class that is inherited
from the class that it was created.
The protected class members are similar to private class members. However, they can be
inherited.
So, we shall be using the protected access specifier for any class member that we want to
encapsulate.
Please note that: we still need to use Properties to access protected class members because technically,
they are still 'private'.
The only difference is that they can be inherited by derived class while private class members cannot be
inherited.
So, they will be inherited. But, we shall use Properties (setter and getter) to access them.
Let us demonstate the use of the protected access specifier.
Let us do some math calculations.
Simple Interest and Amount Calculations
Please review Question (5.) and the solution on Solved Examples on
Simple Interest website:
(www.finance-calculators.appspot.com/simpleInterestApplications.html)
Let us calculate the simple interest and amount for several customers.
We shall use Inheritance to solve that Question for several students.
We shall make the interest rate of the financial institution and the time to be public, but make the first
names of the customers and the principal (sum of money deposited) to be protected.
Please review the screenshots and the comments.
(1.) Coupling of the base class and the derived class: The derived class is dependent on the base class to
the degree that any change in the base class affects the derived class.
Imagine if one deletes a class member of a base class that is also used in the derived class.
For instance, in our demonstration of Multilevel Inheritance; if one of the properties of the Quadrilateral is
deleted, the program will not run.
(2.) Execution time (Run time): It takes more time for an inherited method to execute when compared to a
method that did not use inheritance.
One can write a program that uses a class to calculate the simple interest and amount of an investment without using
inheritance.
(3.) Depending on the compiler, unused base class members is a waste of memory: When a derived class inherits
a base class, it may or may not use all the inherited class members of the base class.
In the event that any base class member is not used in the derived class, it leads to a waste of resource/memory
allocated to that class member. This typically depends on the compiler.
Notice that in our examples, we did not use all the fields of the base class.
So far, we demonstrated the inheritance of the class fields of the base class.
But remember: the methods of the base class can also be inherited.
We discussed the Second Approach to Inheritance
However, in that approach; the base class method and the derived class method had different names:
BaseClassDetails() and DerivedClassDetails().
What if they have the same name and we want different outputs for both methods, what should we do?
When the base class and the derived class have the same method name, the base class method overrides the derived
class method.
When the derived class inherits the method of the base class: and wants to modify the output/return value of
that method using the same name:
We can do it in any of these two ways:
(1.) Include the new keyword to the derived class method.
Then, create two objects: one object of the base class to call the base class method and and another object
of the derived class to call the derived class method.
(2.) Declare the method in the base class with the virtual keyword and declare
the method in the derived class with the override keyword.
Then, create two objects: one object of the base class to call the base class method and and another object
of the derived class to call the derived class method.
By doing so, we can run the methods in both the base class and the derived class.
An example is the event that occurred in July 2020 when Governor Brian Kemp of the U.S State of Georgia banned cities and counties from enforcing a mask mandate.
(www.cbsnews.com/news/georgia-governor-brian-kemp-bans-city-face-mask-orders-coronavirus-pandemic/)
In essence, the governor's executive order of not requiring masks overrides any law/ordinance by cities and counties
requiring masks.
Let us review some code examples. Please review the screenshots and the comments.
Let us assume (and of course the assumption is proper) that the City of Atlanta inherits from the State of Georgia.
Please review the screenshots and the comments.
Same method name: new keyword in the derived class method
Same method name: virtual keyword in the base class method and override keyword in the derived class method
The sealed keyword is used in any base class that does not want any derived class to inherit from it.
In other words, no class can inherit anything from a base class that is declared with the sealed keyword.
A general belief is that the decision of the Supreme Court is sealed. Is that right, people? (But, does the
Supreme Court have the last word? I think Christians would disagree.)
No other court will hear any case decided by the Supreme Court.
Most importantly (Bring it to History as this is an election year): the 2000 Presidential Election
(www.history.com/news/2000-election-bush-gore-votes-supreme-court) was sealed by the Supreme Court.
Let us look at a code example. Please review the screenshots and the comments.
sealed keyword
Because a sealed class cannot be inherited, it cannot be a base class.
Because it cannot be a base class, it cannot be an abstract class. No worries, we shall deal with abstract classes in the next section.
Because it cannot be used as a base class, calling sealed class members can be made faster by some run-time optimizations.
Abstraction is the process of hiding sensitive data while exposing only the required properties and methods.
Compare it to a situation where we have a private class field, but use a public property to access that field
(the Get and Set accessors).
Abstraction is done using:
(1.) Abstract class
(2.) Interface
An abstract class is a class that:
(1.) Is declared using the abstract keyword.
(2.) Cannot be used to create objects.
In other words, it cannot be instantiated directly using the new operator.
Because it cannot be used to create objects, it cannot have a constructor.
(3.) Can be used as a base class or a derived class. Most times, it is used as a base class.
It must be inherited by another class.
But, it can also inherit a class.
When an abstract class inherits a virtual method from a base class, the abstract class can override the
virtual method with an abstract method.
(4.) May contain abstract members (including abstract methods).
If it contains an abstract member, that member must be declared with the abstract keyword.
(5.) May contain non-abstract members.
The reason for using an abstract class is to provide a common definition of a base class that multiple derived classes
can share.
For example: an abstract class can be used as a parameter to several functions of a class library, and require
programmers using that library to implement the class by creating a derived class.
An Abstract method is a method that:
(1.) Is declared using the abstract keyword.
(2.) Have no implementation.
It does not have a body.
Hence, it is followed by a semicolon rather than the normal method block.
The *implementation* of an abstract method is provided by the derived class that inherits it.
Note that the method of the derived class must override that abstract method in order to implement it's
own method (because the abstract method does not have any implementation).
(3.) Must be used only in an abstract class.
A concrete class is a nonabstract class that can instantiate objects.
In other words, it can be instantiated directly using the new operator.
Teacher: Remember we discussed earlier that C# does not support multiple inheritances.
Student: Yes.
C# does not support multiple inheritances. But C++ does.
Teacher: That is correct.
However, C# supports multiple interfaces.
So, if you want to demonstrate multiple inheritances with C#, you can do so with multiple interfaces as
the parents.
An Interface is like an abstract base class that:
(1.) Is declared using the interface keyword.
(2.) Is named using a valid C# identifier and which by convention, must begin with an uppercase I.
(3.) Can contain instance methods, properties, events, indexers, or any combination of these member types.
(4.) Cannot contain instance fields, instance constructors, or finalizers.
However, it may contain static constructors, static fields, constants, or operators.
(5.) Contains definitions for a group of related functionalities that a non-abstract class or struct must implement.
Struct is not covered in this course.
(6.) Is used to simulate inheritance for structs because structs cannot inherit from another struct or class.
Struct is not covered in this course.
(7.) Is inherited using the colon :
Multiple interfaces can be inherited.
C# supports the inheritance of multiple interfaces, but not the inheritance of multiple classes.
(1.) An interface contains only abstract public members.
Any class that implements an interface must implement all the members of that interface.
An interface may define default implementations for some or all of its members.
(2.) An interface cannot be used to create objects.
In other words, it cannot be instantiated directly using the new operator.
The members of an interface are implemented by any class ot struct that implements the interface.
To implement any member of an interface, the corresponding member of the implementing class must be public,
non-static, and have the same name and signature as that interface member.
(3.) A class or struct can implement multiple interfaces.
Further, a class (not a struct) can inherit a base class and also implement multiple interfaces.
Teacher: Let us demonstrate the inheritance of multiple interfaces.
We shall use the same example that we used when we demonstrated Multiple Inheritance in C++
Student: You mean the Zoology example for the dog breeds?
Teacher: Yes.
Multiple Interfaces
Literally: poly means many and morphs means forms; so polymorphism means
many forms
Polymorphism is the ability of classes to:
(I.) Invoke the methods of a derived class by referencing a base class at run time and
(II.) Implement different methods called by the same name at compile time
There are basically two kinds of polymorphism:
(1.) Dynamic Polymorphism
(2.) Static Polymorphism
This polymorphism:
(1.) Occurs at run time
(2.) Also referred to as late binding polymorphism because the decision regarding the method to be called
is made at run time.
(3.) Overrides the method of a base class by using the same name and parameters of that method in a
derived class in order to perform a different task. (Method Overriding)
For this to occur, the method in the base class must use the virtual keyword while the
same method in the derived class must use the override keyword.
Let us demonstrate Dynamic Polymorphism
Back to Geometry: Quadrilaterals
A Quadrilateral is a four-sided polygon.
These figures are Quadrilaterals.
(1.) Square
(2.) Rhombus
(3.) Rectangle
(4.) Parallelogram
(5.) Kite
(6.) Trapezoid
We shall calculate the perimeter of these quadrilaterals.
The formulas for calculating the perimeters of quadrilaterals are found here:
Mensuration Formulas
(www.samuelchukwuemeka.com/Mensuration/formulas.html)
The website also contains the calculators for calculating perimeters.
You may test the output of this program with the Mensuration Calculators
on the website.
We shall list the parameters used for calculating the perimeters of the quadrilaterals.
The parameters are the class fields of the base class: Quadrilateral.cs
Main Class: Program.cs
Base Class: Quadrilateral.cs
Child Class: Square.cs
Child Class: Rectangle.cs
Child Class: Rhombus.cs
Child Class: Parallelogram.cs
Child Class: Trapezoid.cs
Child Class: Kite.cs
To calculate the perimeter of a:
(I.) Square and Rhombus: only a side is needed.
So, we shall define side as one of the class fields of the Quadrilateral
(II.) Rectangle and Parallelogram: the length and the width is needed.
So, we shall include length and width as class fields of the Quadrilateral
(III.) Kite: A kite has two pairs of equal sides.
We shall define them as side1Kite and side2kite and include them as class fields of the Quadrilateral
(IV.) Trapezoid: A trapezoid has no equal side.
The Quadrilateral class fields for these sides are: side1Trapezoid, side2Trapezoid, side3Trapezoid,
and side4Trapezoid
The other class fields we need for the Quadrilateral.cs class are the fields that define the perimeters for each
quadrilateral.
Let us demonstrate Dynamic Polymorphism (Polymorphism at Run-time)
Please review the screenshots and the comments.
Dynamic Polymorphism (Polymorphism at Run-time)
{ public static className operator *operator* (parameters) ...create object ...write code return object }*operator* is the operator to be overloaded.
The correct option is $B$
If you did not answer Option $B$, please review the screenshots and the comments again.
Then, let me know if you have any questions.
Some operators can be overloaded while some cannot.
Let us review those operators that can be overloaded, and those that cannot be overloaded.
(1.) Use any academic field/discipline/area of your interest.
Find any topic(s) in that discipline that you are knowledgeable about/proficient in.
With clear explanations and comments, write programs that demonstrate:
(a.) Inheritance
(b.) Multilevel Inheritance
(2.) Use any academic field/discipline/area of your interest.
Find any topic(s) in that discipline that you are knowledgeable about/proficient in.
With clear explanations and comments, write programs that demonstrate:
(a.) Dynamic Polymorphism
(b.) Method overloading in Static Polymorphism
(c.) Operator overloading in Static Polymorphism
(3.) Using well-written comments, write a program that demonstrates all the five points listed on an
Abstract class
This should include the implementation of at least an abstract method.
(4.)
(1.) If your colleague developed a console application for a program, develop a desktop application for the same program.
(2.) If your colleague developed a desktop application for a program, develop a console application for the same program.
(3.) Rewrite the program of your colleague to display the same output.
(4.) Other substantive responses.
(1.) Grade Point Average (GPA) Calculation for Several Students
Please review Question (7.) on the website: Solved Examples on the Measures of Center
(www.descriptive-statistics.appspot.com/measuresCenter.html)
Review the steps in calculating Rita's GPA.
Use only the five courses listed in the example.
Make the fields: first name and the grade of the student to be protected
You are welcome to make other fields public if you wish.
Write a C# program that uses Multilevel Inheritance to calculate the GPA of Rita and at least one other student simultaneously (at the same time)
Use the same numbers in Question (7.) to calculate Rita's GPA.
For the other student, use a fictitious name or Nameless; and use every grade: $A, B, C, D, F$ in the calculation.
For example: the student should make an $A$ in one course, a $B$ in one course, a $C$ in one course, a $D$ in one course
and an $F$ in one course.
The output of your program should include the information in the table as seen in the solution for Question (7.):
(a.) the name of the student
(b.) the each course and the grade for each course
(c.) the corresponding point for the grades
(d.) the credit hour for each course
(e.) the sum of the credit hours
(f.) the corresponding grade points
(g.) the sum of the grade points
(h.) the GPA
Do you understand the information in that table?
The user (student) should be able to look at your output and understand the GPA calculation very well.
These are the minimum requirements.
You may wish to give recommendation and advice among others to the user/student based on the grade and/or the GPA.
(2.) Please review these two examples:
(I.) How to explicitly implement interface members
(www.docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/how-to-explicitly-implement-interface-members) and
(II.) How to explicitly implement members of two interfaces
(www.docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/how-to-explicitly-implement-members-of-two-interfaces) then write the program:
Grade Point Average (GPA) Calculation for Several Students
Please review Question (7.) on the website: Solved Examples on the Measures of Center
(www.descriptive-statistics.appspot.com/measuresCenter.html)
Review the steps in calculating Rita's GPA.
Use only the five courses listed in the example.
Write a C# program that uses Multiple Interfaces to calculate the GPA of Rita and at least one other student simultaneously (at the same time)
Use the same numbers in Question (7.) to calculate Rita's GPA.
For the other student, use a fictitious name or Nameless; and use every grade: $A, B, C, D, F$ in the calculation.
For example: the student should make an $A$ in one course, a $B$ in one course, a $C$ in one course, a $D$ in one course
and an $F$ in one course.
The output of your program should include the information in the table as seen in the solution for Question (7.):
(a.) the name of the student
(b.) the each course and the grade for each course
(c.) the corresponding point for the grades
(d.) the credit hour for each course
(e.) the sum of the credit hours
(f.) the corresponding grade points
(g.) the sum of the grade points
(h.) the GPA
Do you understand the information in that table?
The user (student) should be able to look at your output and understand the GPA calculation very well.
These are the minimum requirements.
You may wish to give recommendation and advice among others to the user/student based on the grade and/or the GPA.
TextBook Questions.
(3.) Question (6.) on Page 478.
(4.) Question (9.) on Page 479.
object, array, array as object, array of objects, array class, tuple, tuple class, tuple object, tuple of objects, helper method, System.Linq namepspace, 1-tuple, singleton, 2-tuple, pair, 3-tuple, triple, 4-tuple, quadruple, 5-tuple, quintuple, 6-tuple, sextuple, 7-tuple, septuple, 8-tuple, octuple,
Students will:
(1.) Discuss arrays as objects.
(2.) Discuss arrays of objects.
(3.) Discuss array class.
(4.) Implement array class methods.
(5.) Write a program that uses arrays of objects to solve a real-world problem.
(6.) Discuss tuple class.
(7.) Create tuple objects.
(8.) Write a program that uses tuple class to solve a real-world problem.
(9.) Implement the methods of the clasess and interfaces of the System.Linq namespace.
(1.) Textbook Chapter
(2.) Arrays
(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/)
(3.) Array Class
(https://docs.microsoft.com/en-us/dotnet/api/system.array?view=netcore-3.1)
(4.) Tuple Class
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple?view=netcore-3.1)
(5.) System.Linq Namespace
(https://docs.microsoft.com/en-us/dotnet/api/system.linq?view=netcore-3.1)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(6.) Type C# Array Class and/or C# Array of Objects in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(7.) Type C# Array Class and/or C# Array of Objects in the search bar and view/read the results.
We discussed Arrays in the previous course: C# (Beginning C#)
(1.) There, we learned that arrays are data structures for storing multiple variables of the same data type.
(2.) We also learned that we declare arrays by specifying the type of its elements.
(3.) We learned about single-dimensional arrays, multidomensional arrays, and jagged arrays.
(4.) The number of dimensions and the length of each dimension are established when the array instance is created.
Once the array instance is created, the number of dimensions and the length of each dimension cannot be changed during the
lieftime of the instance.
(5.) Arrays are zero-indexed. The first element in the array is at index: $0$ and the last element is at index: $n-1$
where $n$ is the length or size of the array... among others.
We discussed Classes and Objects in this course: Advanced C#
Here, we shall discuss Arrays of Objects.
(6.) Arrays are objects. Yes, we can implement them as objects.
(7.) We can use array to store elements of different types (not only elements of the same type).
To do so, we need to specify object as its type.
(8.) The default values of numeric arrays elements are set to $0$, while the reference elements are set to null
(9.) Array types are reference types.
Variables of reference types store references to their objects. Two variables can reference the same object. Operations on one
variable can affect the object referenced by the other variable.
(10.) Array is the abstract base type through which all the array types are derived from.
The Array type implements the IEnumerable Interface and the IEnumerable<T> Interface.
Hence, the foreach loop can be used on all C# arrays.
We can use the properties and members of the Array class.
To demonstrate arrays as objects, we simply declare them with the new keyword, specify the type, and initialize them.
Please review the screenshots and the comments.
Array as Objects
Let us create a class that implements an array of objects.
Please review the screenshots and the comments.
Array of Objects Application: Compound Amount Calculations
As you can see from the codes in the screenshots, we can change the values of any of those array elements if we want to.
Besides that, can you guess the time it took the compiler to do these calculations?
If the unit of your time is in seconds, you are correct.
The Array Class provides the methods for creating, manipulating, searching,
and sorting arrays.
It is the base class for all arrays in the common language runtime.
Please review the implementation of the methods of the Array class.
Array Class
https://docs.microsoft.com/en-us/dotnet/api/system.array?view=netcore-3.1)
We discussed Tuples in the previous course: C# (Beginning C#)
There, we learned that tuples:
(1.) Are data structures for storing multiple variables of the same or different data types.
(2.) Have a specific number and sequence of elements.
(3.) Can be nested.
(4.) Provides easy access to a dataset and manipulation of the dataset.
(5.) Can return multiple values from a method without using the out parameters.
(6.) Can pass multiple values to a method through a single parameter.
(7.) Can be returned from a method using the out parameter...among others.
var objectName = Tuple.Create(value1, value2, value3, ...);(2.) Calling the tuple class constructor.
var objectName = new Tuple<dataType1, dataType, dataType3, ...> (value1, value2, value3, ...)Teacher: Which approach do you prefer?
Creating Tuple Objects
First Approach: Helper Method
Second Approach: Class Constructor
Let us create a tuple class application.
Please review the screenshots and the comments.
Application of Tuple Class: Compound Amount and Compound Interest Calculations
As you can see from the codes in the screenshots, we can change the values of any of those tuple elements
if we want to.
Please review the implementation of the examples and methods of all the Tuple classes.
These include the:
(1.) 1-tuple or Singleton:
Tuple<T1> Class
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-1?view=netcore-3.1)
(2.) 2-tuple or Pair:
Tuple<T1, T2> Class
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-2?view=netcore-3.1)
(3.) 3-tuple or Triple:
Tuple<T1, T2, T3> Class
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-3?view=netcore-3.1)
(4.) 4-tuple or Quadruple:
Tuple<T1, T2, T3, T4> Class
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-4?view=netcore-3.1)
(5.) 5-tuple or Quintuple:
Tuple<T1, T2, T3, T4, T5> Class
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-5?view=netcore-3.1)
(6.) 6-tuple or Sextuple:
Tuple<T1, T2, T3, T4, T5, T6> Class
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-6?view=netcore-3.1)
(7.) 7-tuple or Septuple:
Tuple<T1, T2, T3, T4, T5, T6, T7> Class
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-7?view=netcore-3.1)
(8.) 8-tuple or Octuple:
Tuple<T1, T2, T3, T4, T5, T6, T7, T8> Class
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-8?view=netcore-3.1)
where:
T1 is the type of the first component of the tuple
T2 is the type of the second component of the tuple
T3 is the type of the third component of the tuple
T4 is the type of the fourth component of the tuple
T5 is the type of the fifth component of the tuple
T6 is the type of the sixth component of the tuple
T7 is the type of the seventh component of the tuple
T8 is the type of the eighth component of the tuple
TRest is any generic Tuple object that defines the types of the tuple's remaining components.
Student: Is that all?
Keep going...so much you want us to learn
Teacher: No worries... you can stop here.
The static helper method of the tuple class does not support the creation of tuple objects with more than
eight components.
Notice that in the example we did, the tuple object output was seven components.
Try to keep it at seven components.
Student: What if we wanted more?
Teacher: Use array of objects.
Student: But, what if I wanted to use tuple objects?
Teacher: Then you have to use the tuple class constructor.
But, that is cumbersome.
To create an n-tuple with nine or more components, you must call the Tuple<T1,T2,T3,T4,T5,T6,T7,TRest> constructor.
(1.) DB Requirement Number (3.) is required.
In other words, you may not implement any method already implemented by any of your colleagues.
The Array Class in C# provides the methods for creating, manipulating, searching,
and sorting arrays.
Array Class
(https://docs.microsoft.com/en-us/dotnet/api/system.array?view=netcore-3.1)
Please review the implementation of the methods of the Array class.
Implement any five methods
(2.) DB Requirement Number (3.) is required.
In other words, you may not implement any method already implemented by any of your colleagues.
The System.Linq namespace in C# provides classes and interfaces that support queries that use Language-Integrated Query (LINQ).
System.Linq Namespace
(https://docs.microsoft.com/en-us/dotnet/api/system.linq?view=netcore-3.1)
Please review the implementation of the methods of any class or interface of the System.Linq namespace.
Implement any five methods
(3.)
(1.) Rewrite the program of your colleague using a different method to display the same output.
(2.) If your colleague developed a console application for a program, develop a desktop application for the same program.
(3.) If your colleague developed a desktop application for a program, develop a console application for the same program.
(4.) Other substantive responses.
(1.) Please review the example I did in the Array of Objects
The objects are the elements of the array. Hence, it is referred to as Array of Objects.
Extend the application by adding user-input for each class member of the objects of the array.
The same output should be displayed.
(2.) Grade Point Average (GPA) Calculation for Several Students
Please review Question (7.) on the website: Solved Examples on the Measures of Center
(https://descriptive-statistics.appspot.com/measuresCenter.html)
Review the steps in calculating Rita's GPA.
Use only the five courses listed in the example.
Make the fields: first name and the grade of the student to be protected
You are welcome to make other fields public if you wish.
Write a C# program that uses Arrays of Objects to calculate the GPA of Rita and at least one other student simultaneously (at the same time)
Use the same numbers in Question (7.) to calculate Rita's GPA.
For the other student, use a fictitious name or Nameless; and use every grade: $A, B, C, D, F$ in the calculation.
For example: the student should make an $A$ in one course, a $B$ in one course, a $C$ in one course, a $D$ in one course
and an $F$ in one course.
The output of your program should include the information in the table as seen in the solution for Question (7.):
(a.) the name of the student
(b.) the each course and the grade for each course
(c.) the corresponding point for the grades
(d.) the credit hour for each course
(e.) the sum of the credit hours
(f.) the corresponding grade points
(g.) the sum of the grade points
(h.) the GPA
Do you understand the information in that table?
The user (student) should be able to look at your output and understand the GPA calculation very well.
These are the minimum requirements.
You may wish to give recommendation and advice among others to the user/student based on the grade and/or the GPA.
(3.) Grade Point Average (GPA) Calculation for Several Students
Please review Question (7.) on the website: Solved Examples on the Measures of Center
(https://descriptive-statistics.appspot.com/measuresCenter.html)
and the:
Example of the $4-tuple$ implementation
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-4?view=netcore-3.1)
Review the steps in calculating Rita's GPA.
Use only the five courses listed in the example.
Make the fields: first name and the grade of the student to be protected
You are welcome to make other fields public if you wish.
Write a C# program that uses Tuples Class to calculate the GPA of Rita and at least one other student simultaneously (at the same time)
Use the same numbers in Question (7.) to calculate Rita's GPA.
For the other student, use a fictitious name or Nameless; and use every grade: $A, B, C, D, F$ in the calculation.
For example: the student should make an $A$ in one course, a $B$ in one course, a $C$ in one course, a $D$ in one course
and an $F$ in one course.
The output of your program should include the information in the table as seen in the solution for Question (7.):
(a.) the name of the student
(b.) the each course and the grade for each course
(c.) the corresponding point for the grades
(d.) the credit hour for each course
(e.) the sum of the credit hours
(f.) the corresponding grade points
(g.) the sum of the grade points
(h.) the GPA
Do you understand the information in that table?
The user (student) should be able to look at your output and understand the GPA calculation very well.
These are the minimum requirements.
You may wish to give recommendation and advice among others to the user/student based on the grade and/or the GPA.
(4.) The System.Linq namespace in C# provides classes and interfaces that support queries that use Language-Integrated Query (LINQ).
One of those classes is the Enumerable class.
Please review the implementation of two of the methods of the Enumerable class:
(I.) Enumerable.Any Method
(https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netcore-3.1) and
(II.) Enumerable.Sum Method
(https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum?view=netcore-3.1) then write the program:
Grade Point Average (GPA) Calculation for Several Students
Please review Question (7.) on the website: Solved Examples on the Measures of Center
(https://descriptive-statistics.appspot.com/measuresCenter.html)
Review the steps in calculating Rita's GPA.
Use only the five courses listed in the example.
Write a C# program that uses any of the methods of the Enumerable Class and/or any method of any of the
classes or interfaces of the System.Linq namespace to calculate the GPA of Rita and at least one other
student simultaneously (at the same time)
Use the same numbers in Question (7.) to calculate Rita's GPA.
For the other student, use a fictitious name or Nameless; and use every grade: $A, B, C, D, F$ in the calculation.
For example: the student should make an $A$ in one course, a $B$ in one course, a $C$ in one course, a $D$ in one course
and an $F$ in one course.
The output of your program should include the information in the table as seen in the solution for Question (7.):
(a.) the name of the student
(b.) the each course and the grade for each course
(c.) the corresponding point for the grades
(d.) the credit hour for each course
(e.) the sum of the credit hours
(f.) the corresponding grade points
(g.) the sum of the grade points
(h.) the GPA
Do you understand the information in that table?
The user (student) should be able to look at your output and understand the GPA calculation very well.
These are the minimum requirements.
You may wish to give recommendation and advice among others to the user/student based on the grade and/or the GPA.
(5.) Measures of Center and Measures of Dispersion of Data
Please give an appropriate name for your dataset.
An even-sized dataset and an odd-sized dataset is required.
Calculations of the measures of center and the measures of spread are required.
Please test your program for an even-sized dataset and an odd-sized dataset.
Please review the:
Measures of Center
(https://descriptive-statistics.appspot.com/#formulasMeasuresCenter)
and the:
Measures of Spread
(https://descriptive-statistics.appspot.com/#formulasMeasuresSpread)
and the:
Examples of the Final Project for the Measures of Center and the Measures of Spread
(https://descriptive-statistics.appspot.com/project.html)
and the:
Example of the 3-tuple implementation
(https://docs.microsoft.com/en-us/dotnet/api/system.tuple-3?view=netcore-3.1)
(I.) Using 3-tuple class and any dataset that
has at least a size of six (sample size of $6$) for an even-sized dataset; calculate the measures of center
and the measures of spread of the dataset.
(II.) Using $3-tuple$ class and any dataset that
has at least a size of six (sample size of $7$) for an odd-sized dataset; calculate the measures of center
and the measures of spread of the dataset.
You can use any made-up dataset for this assignment.
However, for your final project; your dataset must be verifiable.
file, stream, file and stream I/O, System.IO namespaces, storage, backing store, byte, directory path, disk storage, file name, directory name, file stream, File class, FileInfo class, FileStream class, TextReader class, TextWriter class, StringReader class, StringWriter class, StreamReader class, StreamWriter class, ReadAllText method, ReadAllLines method, WriteAllText method, WriteAllLines method, AppendAllText method, AppendAllLines method, sequential access file, synchronous file operations, random access file processing, text file processing, object-based file processing, BinaryReader class, BinaryWriter class
Students will:
(1.) Write programs that reads text from a text file.
(2.) Write programs that writes text to a text file.
(3.) Write programs that appends text to a text file.
(4.) Write programs that reads characters from a string.
(5.) Write programs that writes characters to a string.
(6.) Implement the methods of the File class.
(7.) Implement the methods of the FileInfo class.
(8.) Implement the methods of the FileStream class.
(1.) File and Stream I/O
(www.docs.microsoft.com/en-us/dotnet/standard/io/)
(2.) File Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.file?view=netframework-4.8)
(3.) FileInfo Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netcore-3.1)
(4.) FileStream Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netframework-4.8)
(5.) Read from Text Files:
(I.) https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-read-text-from-a-file
(II.) https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-from-a-text-file
(6.) Write and Append to Text Files:
(I.) https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
(II.) https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
(7.) Read Characters from a String
(www.docs.microsoft.com/en-us/dotnet/standard/io/how-to-read-characters-from-a-string)
(8.) Write Characters to a String
(www.docs.microsoft.com/en-us/dotnet/standard/io/how-to-write-characters-to-a-string)
(9.) StringReader Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.stringreader?view=netcore-3.1)
(10.) StringWriter Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.stringwriter?view=netcore-3.1)
(11.) BinaryReader Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.binaryreader?view=netcore-3.1)
(12.) BinaryWriter Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.binarywriter?view=netcore-3.1)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(13.) Type C# Files and Streams in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(14.) Type C# Files and Streams in the search bar and view/read the results.
A file is an ordered and named collection of bytes that has a storage medium.
Working with files implies working with directory paths, disk storage, and file and directory names.
A stream is a sequence of bytes that is used to read from, and write to a storage medium.
Streams involve three fundamental operations.
These operations are:
(1.) Reading: This involves the transfer of data from a stream into a data structure, such as an array of bytes.
(2.) Writing: This involves the transfer of data to a stream from a data source.
(3.) Seeking: This involves the querying and modifying of the current position within a stream.
The storage medium is also known as backing store.
These include disks and memory among others.
File and stream I/O (Input/Output) is the transfer of data to, or from a storage medium.
The System.IO namespaces in the .NET Framework contain types that enable reading and writing, both
synchronously and asynchronously, on files and streams.
For Files:
The System.IO namespace provide types that:
(1.) Get and set properties for files.
(2.) Retrieve collections of files based on search criteria.
For Streams:
The System.IO namespace provide types that:
(1.) Read encoded characters from streams.
(2.) Write encoded characters to streams.
Under the System.IO namespace, there are several classes.
In this module, we shall only focus on these classes.
File and Directory Classes
(1.) File Class (https://docs.microsoft.com/en-us/dotnet/api/system.io.file?view=netframework-4.8)
(2.) FileInfo Class (https://docs.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netcore-3.1)
Stream Class
(3.) FileStream Class (https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netframework-4.8)
Reader and Writer Classes
(4.) TextReader Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.textreader?view=netcore-3.1)
and
TextWriter Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.textwriter?view=netcore-3.1)
(5.) StringReader Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.stringreader?view=netcore-3.1)
and
StringWriter Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.stringwriter?view=netcore-3.1)
(6.) StreamReader Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=netcore-3.1)
and
StreamWriter Class
(www.docs.microsoft.com/en-us/dotnet/api/system.io.streamwriter?view=netcore-3.1)
Sequential access file processing is the ability of the computer to read or write to the file sequentially
(from beginning to end).
These are common with text files.
Compare sequential access file processing with synchronous file operation.
Random access file processing is the ability of the computer to read or write to the file anywhere (at any
position) in the file. These are common with database files.
Be it as it may, the computer can read sequential files randomly, as well as read random files sequentially.
We studied: Strings, Booleans, Date and Time and Arrays in the Beginning C#.
We studied: Array Class and Tuple Class in the previous module in this Advanced C#.
We have also reviewed several String methods/functions.
We shall use some our prior knowledge from those topics, in this module.
For this module, we are only concerned with synchronous file operations (read synchronously, write synchronously, append synchronously).
This approach has a limitation: the storage/location of your file.
We shall use the StreamReader class to read a text file.
It reads a text file one line at a time. However, we have to save our file in a particular location in order to read
it.
Pick any topic in an academic area/field/discipline of your choice.
I am going to write some notes about our next module: XAML: Extensible Application Markup Language
But, you may choose whatever you want, provided it is in an academic discipline.
The steps are:
(1.) Create a text file about the topic: say Module7Notes.txt
(2.) Write some notes in the file. I shall write five sentences.
This is what I wrote:
(1.) XAML is an acronym which stands for eXtensible Markup Application Language.
(2.) It is pronounced as "Zamel".
(3.) It is a declarative markup language used for creating a user interface for a .NET Core app.
(4.) The files are XML files but with .xaml extension.
(5.) It was developed by Microsoft.
(3.) Open the Visual Studio IDE.
(4.) Add the System.IO namespace by writing using System.IO
(5.) Important: Please make sure you save your file where the IDE would easily access it.
When you created the C# application, you named the application.
I named my application: FileStream
Go to the location of your application. My applications are in the Documents folder of my C: drive.
Click the application folder: FileStream
Then, click the bin folder, then the Debug folder, then the netcoreapp3.1 folder, and drop your
text file Module7Notes.txt there.
WindowsC: ---> Users ---> chukw ---> Documents ---> C# ---> FileStream ---> bin ---> Debug ---> netcoreapp3.1
---> Module7Notes.txt
The location is: C:\Users\chukw\Documents\C#\FileStream\bin\Debug\netcoreapp3.1\Module7Notes.txt
(6.) Please review the screenshots and the comments.
Student: I do not like this approach.
The file path stuff for the file.
Why can't I just save my file wherever I want it to be?
Teacher: You are not alone.
I do not like it either.
Let us look at another approach.
In this second approach, you can save your file where you like and read it from there.
I prefer this approach.
It reads the contents of a text file by using the static methods: ReadAllText and ReadAllLines from
the System.IO.File class
We can save our file whereever we want on the C: drive, and read it from there.
Also, we do not need to include the System.IO.File namespace as we did in the first approach.
I shall not include it. But you may include it if you want to.
So, we shall copy the file: Module7Notes.txt from where we saved it and save it in a new location.
The new location is: C:\Users\chukw\OneDrive\Documents\C#\Files and Streams\Module7Notes.txt
As you can see: I saved it in the Files and Streams folder of the C# folder of the Documents File and folder of the
OneDrive on my computer.
Yes, I saved it in the cloud.
Yes, I can make changes to it (append some texts to it) in the cloud.
The easy way to figure out the path/location of your file is: Right-click the file; click the Properties icon; and
copy the Location. You do want to make sure you include the file name to the path in the program.
When using the ReadAllText method of the System.IO.File class, it is important to enclose the path/location
of the file enclosed in double quotes, and include the at symbol, @ before it.
Please review the screenshot and the comments.
We shall use the StreamWriter class to create a new text file and write to it.
Student: But, why not just write to the one we created already?
Teacher: Good question.
This is because once we write to it, it will erase everything we had already.
Student: What if we wanted to add more notes to the file we just read?
Teacher: You are asking good questions.
We shall append notes to it.
Rather than write to it, we shall append to it.
Student: Why did you decide to use the ReadAllLines method this time?
Teacher: When we use the StreamWriter class to write to a new file, that file is saved in the
Documents folder of the Windows (C:) drive by default.
C:\Users\chukw\Documents\...the...new...file
Because of the location where it is saved, we cannot use the StreamReader class to read it.
Student: I am not talking about the StreamReader class though.
I am asking why you want to use ReadAllLines method rather than the one we used earlier: the
ReadAllText method
Teacher: The StreamWriter class uses a foreach loop to write contents to a file because we
use an array to write the contents.
The ReadAllLines method reads each line of a file into an array. Each element of the array is one line of
the file.
Because of that, we also use a foreach loop to read each line of the file.
In that regard, I prefer using the ReadAllLines method to read whatever I write with the StreamWriter
class becuase they both use an array and a foreach loop.
Notice that the ReadAllText method did not use an array.
Let us use another topic from another field.
We shall include the System.IO.File namespace because we want to use the StreamWriter class directly.
This is one of the acronyms I learned in Elementary School: Characteristics of Living Things: MRNIGER.
Please review the screenshots and the comments.
NOTE:
Whenever you write to a file, it is very important you close the file before reading it.
So, did we close the file before reading it?
As seen from the code: the StreamWriter object, writeFile is declared and instantiated in the
using statement.
Because of this, the Dispose method is invoked.
The Dispose method automatically flushes and closes the stream.
Hence, the file was actually closed before we read it.
Student: Mr. C, you are aware you did not complete the listing.
Teacher: Yes Sir. I am aware.
Guess I did it intentionally.
Student: Why?
To show the Append method?
Teacher: To show the Append operation.
We have already created the LivingThings.txt file.
However, what we listed in that file is incomplete.
We need to complete it.
So, we need to append some texts to it.
If you are appending each characteristic to a new line, use the WriteLine method for each characteristic
If you are appending some texts to a characteristic on the same line, use the Write method.
After appending the texts, we shall read the entire file.
Please review the screenshots and the comments.
NOTE:
Whenever you write to a file, it is very important you close the file before reading it.
Appending to a file is actually writing to an existing file.
So, did we close the file before reading it?
As seen from the code: the StreamWriter object, writeFile is declared and instantiated in the
using statement.
Because of this, the Dispose method is invoked.
The Dispose method automatically flushes and closes the stream.
Hence, the file was actually closed before we read it.
Besides the StreamWriter class for writing and appending to files, we can also the WriteAllText method
and the AppendAllText method of the File class
The WriteAllText method creates, writes, and closes the file automatically.
The AppendAllText method opens, writes, and closes the file automatically.
So, you do not need to call the Flush() or Close() method.
Let us use a quote from Martin Luther King Jr.
We shall write the incomplete quote.
Then, append some text to complete it.
Then, read the quote.
Do not forget the escape sequence for including double quotes
Student: If we want to append more lines rather than just text, we shall use the AppendAllLines
method and the ReadAllLines method?
Teacher: That is correct!
Let us do a case where we use the AppendAllLines method
We are doing these various examples with several approaches so you can choose which one you prefer.
The inclusion of the System.IO.File namespace is not required for this approach because the approach I want
to use here would allow me to save the file on OneDrive (my preference). You can save it whereever you wish.
So, I shall not be including that namespace.
But, you may choose to include it if you wish. It does not matter.
We shall use the: WriteAllLines method, AppendAllLines method, and the ReadAllLines method in
this approach.
Student: Which example will you use this time?
Teacher: Guess what I'm thinking?
Student: What?
Teacher: About a mnemonic we learned in Junior Secondary School in Nigeria
Junior Secondary School in Nigeria is equivalent to Middle School in the United States.
Student: What is the mnemonic?
Teacher: The mnemonic that helped us to write the first twenty elements of the Periodic Table?
I even made a YouTube video about it.
Student: Interesting.
Where is the video?
Can you write the elements off hand?
Teacher: Sure 😊
The link is: 1st 20 Elements of the Periodic Table
Let us write the first the mnemonic, the element, and the symbol for the first ten elements.
Then, append the same for the last ten elements.
Then, read the file.
We shall name the file: Elements.txt and save it in this location:
C:\Users\chukw\OneDrive\Documents\C#\Files and Streams\Elements.txt
Let's do it.
The WriteAllLines method creates, writes, and closes the file automatically.
The AppendAllLines method opens, writes, and closes the file automatically.
So, you do not need to call the Flush() or Close() method.
Which of these approaches do you prefer?
(1.) Use any academic field/discipline/area of your interest.
Find any topic(s) in that discipline that you are knowledgeable about/proficient in.
With clear explanations and comments, write programs that:
(a.) Writes text to a text file
(b.) Appends text to the text file
(c.) Reads from the text file.
Use any approach you prefer.
Cite your source(s) accordingly.
(2.) Please review the File Class
(https://docs.microsoft.com/en-us/dotnet/api/system.io.file?view=netframework-4.8)
Review the implementation of the methods of the File class.
Implement any two methods
(3.) Please review the FileInfo Class
(https://docs.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netcore-3.1)
Review the implementation of the methods of the FileInfo class.
Implement any two methods
(4.) Please review the FileStream Class
(https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netframework-4.8)
Review the implementation of the methods of the FileStream class.
Implement any two methods
(5.) Please review the StringReader Class
(https://docs.microsoft.com/en-us/dotnet/api/system.io.stringreader?view=netcore-3.1)
Review the implementation of the methods of the StringReader class.
Implement any two methods
(6.) Please review these documents:
(I.) Read Characters from a String
(https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-read-characters-from-a-string)
and
(II.) Write Characters to a String
(https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-write-characters-to-a-string)
Using at least one (one or more) appropriate string(s):
(a.) Write characters to the string.
(b.) Read characters from the string.
(7.) Please review the BinaryReader Class
(https://docs.microsoft.com/en-us/dotnet/api/system.io.binaryreader?view=netcore-3.1)
Review the implementation of the methods of the StringReader class.
Implement any two methods
(8.) Question (2.) on Page 692 of your textbook.
(1.) Use any method besides the one used by your colleague to display the same output as the program of your
colleague.
(2.) If your colleague attempted Question (1.); use any method that you learned in any of the classes to work
on the same file used by your colleague.
(1.) Please review the screenshots in Example $4$
Use the same file name.
The same output is required.
The spacing and format of that output is required.
There are two columns after the third line sentence in that output: one column is for the acronym (letters) and the
other column is for the characteristics (words).
Write a file that has only the sentences and the words without the acronym.
Insert each letter of the acronym to the corresponding characteristic (word) in each line.
Include clear explanations as comments in your program regarding the method(s) that you used to do it.
Read the file.
(2.) Please review the screenshots in Example $6$
Use the same file name.
The same output is required.
The spacing and format of that output is required.
There are three columns after the first line sentence as well as three columns after the
second line sentence in that output: the first column is for the Mnemonic, the second column is for the
and the Element, and the third column is for the Symbol.
Write a file that has only the sentences, the mnemonic, and the elements without the symbols.
Insert each symbol to the corresponding element in each line.
Include clear explanations as comments in your program regarding the method(s) that you used to do it.
Read the file.
(3.) Please review the Reading Contents From PDF, Word, Text Files In C#
(https://www.c-sharpcorner.com/blogs/reading-contents-from-pdf-word-text-files-in-c-sharp1)
Using appropriate contents:
(a.) Read the contents from a Word document file.
(b.) Read the contents from a pdf (portable document format) file.
(4.) Question (4.) on Page 693 of your textbook.
(5.) Questions (5.) and (6.) on Page 693 of your textbook.
Extensible Markup Language (XML), Extensible Application Markup Language (XAML), Windows Presentation Foundation (WPF) desktop application,
Students will:
(1.) Discuss the Extensible Application Markup Language.
(2.) Develop a Windows Presentation Foundation (WPF) desktop application using the Extensible Application Markup Language.
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(1.) Type XAML or Extensible Application Markup Language in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(2.) Type XAML or Extensible Application Markup Language in the search bar and view/read the results.
(4.) Tutorials by Microsoft: Extensible Application Markup Language (XAML)
(https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/)
(5.) Tutorials by Microsoft: Tutorial: Create your first WPF application in Visual Studio 2019
(https://docs.microsoft.com/en-us/dotnet/desktop/wpf/getting-started/walkthrough-my-first-wpf-desktop-application?view=netframeworkdesktop-4.8)
(6.) Tutorials by Microsoft: Technical Documentation for Microsoft Extensible Application Markup Language (XAML)
(https://www.microsoft.com/en-us/download/details.aspx?id=19600)
My dear, please check the Assess tab.
Your application should be user-friendly and pleasing to the eye (aesthetics).
Your application should work as expected. (functionality).
You may use Functional Programming and/or Object-oriented Programming.
(1.) Develop a Windows Presentation Foundation (WPF) desktop application on any three different topics/concepts in
three different modules for the course.
In other words, for any three modules, find a concept in each module.
This implies three different concepts: one concept per module.
Please make sure you write the module number and the concept
Use at least one button for each concept.
You have the choice to use, or not to use, an input-output feature.
(2.) Develop a Windows Presentation Foundation (WPF) desktop application for the Body Mass Index (BMI) application discussed
in Module 2.
Do this for the United States System (Customary System).
Please note that this application require an input-output feature.
(3.) Develop a Windows Presentation Foundation (WPF) desktop application for the Body Mass Index (BMI) application discussed
in Module 2.
Do this for the International System (Metric System).
Please note that this application require an input-output feature.
There are four options for your Final Exam
Please choose only one option.
This option is based on your textbook (MindTap course).
This implies that it is not free.
However, you have two-weeks free access.
So, it is free if you can complete all the graded assessments in two weeks.
Please click the Gradebook and complete all the assessments there.
All the assessments in the Gradebook are automatically graded.
All those assessments count for the Final Exam and the Final Project.
Access the MindTap Course
Course Key: MTPPFXGQ2HX2
This exam is designed to assess your understanding of the advanced C# concepts.
You have reviewed several topics and several concepts in each topic for seven modules.
Pick at least 1 concept in at least 1 topic in each of the 7 modules.
That gives at least 8 concepts in 7 different topics in 7 modules.
Find two more concepts in any topic in any module.
That gives 10 concepts.
For each concept, please:
(1.) Write at least three sentences about that concept.
(2.) Develop a program about that concept.
In other words, write at least one code example about the concept.
Run the code.
Display the output.
Deliverables:
(1.) 10 concepts in 10 different topics for 7 modules
Please write the: Module number, the Topic, and the Concept
(2.) Three sentences for each concept.
(3.) Code for each concept.
(4.) Output for each concept.
Please submit all these information as a zipped folder (.zip only) in the Final Exam folder of the Blackboard course.
Candidates for this exam are seeking to prove core software development skills. It is recommended that candidates be
familiar with the concepts of and have hands-on experience with the technologies described here either by taking
relevant training courses or by working with tutorials and samples available on MSDN and in Microsoft Visual Studio.
Candidates are expected to have some experience with C# or Microsoft Visual Basic.NET
Please review some of the questions and answers of the
Microsoft Software Development Fundamentals Exam
(https://www.itexams.com/exam/98-361)
This is Free But Requires Patience
Focus on what we covered (Advanced C#).
However, you are welcome to review all of them and attempt only the Advanced C# topics.
Student: Mr. C, you are giving us a final exam with the answers?
How nice of you?
Teacher: Yes of course, I am nice. 😊
But, please read on.
First-come, first-served basis
A particular question may NOT be done by more than one student.
In other words, no two or more students are permitted to do the same question.
Please:
(1.) Pick any five questions.
(2.) Go to the Final Exam Questions forum of the Blackboard course.
(3.) Write the question numbers in that forum only if it has not been written by any other student.
In other words, you need to review any questions posted by your colleagues and make sure that you do not attempt
the same question.
(4.) Explain the solutions of those five questions using your own explanations
and your code examples.
(5.) Number the questions, the solutions, your code examples, and your
explanations based on the actual question numbers.
(6.) Submit the actual questions, the corresponding numbered solutions, your
corresponding numbered explanations and your corresponding code examples and any other relevant
information in the Final Exam folder of the Blackboard course.
(7.) Make your work easy for me to grade.
In other words, write detailed clear specific explanations.
Do not give me any avenue to deduct points.
(1.) Option 3: Sample 1
There are four options for your Final Project.
Please choose only one option.
This option is based on your textbook (MindTap course).
This implies that it is not free.
However, you have two-weeks free access.
So, it is free if you can complete all the graded assessments in two weeks.
Please click the Gradebook and complete all assessments there.
Access the MindTap Course
Course Key: MTPPFXGQ2HX2 (Did you notice it three times in this document?)
It is important you communicate with me for approval prior to doing this project.
Because the course deals with only desktop applications and console applications,
(rather than web applications and mobile applications), you may not do any project that requires a web server
such as contact forms and registration forms among others.
The final project is designed to assess problem-solving skills using the knowledge you have acquired in the
course.
In that regard, solving at least a real-world problem using the knowledge gained in the course is expected.
(1.) Think about any of these companies: our Institution: Kent State University; your local campus; your work place; public and
private schools (excluding home schools); organizations, firms, and businesses
(excluding controversial firms and the like).
Any company you choose should have a verifiable website.
The direct link of the company's website is required.
(2.) Identify a problem on the website that you want to solve.
The problem must be solved by programming using the knowledge acquired from any of the course
topics/concepts/description/learning objectives.
Think about your Midterm Project. You solved a problem: calculating bills, federal taxes, etc.
(3.) Develop the computer program to solve the problem.
Test the program to ensure that it works.
Write detailed comments as applicable.
(4.) Prepare a Documentation Manual/Reflection for the project.
Please cite your sources accordingly.
What is the company?
What is their website?
What problem did you identify?
Did you solve the entire problem or part of the problem?
What course topics/concepts/description/learning objectives did you apply in solving the problem?
How did you solve the problem?
Did you encounter any issues while trying to solve the problem?
Are there any limitations to the project?
Are there any recommendations to the company?
Deliverables:
(1.) Program (all files)
(2.) Clear screenshots of your program (code and output)
(3.) Project Reflection/Documentation Manual
Please submit all these information as a zipped folder (.zip only) in the Final Project folder of the Blackboard course.
The final project is designed to assess your understanding and analysis of data using the knowledge you have
acquired in the course.
Please:
(1.) Visit my website on: Descriptive Statistics
(2.) Review the information for a good understanding of Descriptive Statistics.
It is highly likely that you have a prior knowledge of this topic. Is that right?
(3.) Click the Project link.
(4.) Review the Project Examples. Ensure you follow all the instructions and directions.
(5.) Complete the Final Project for your course.
(6.) Ask questions. I can help.
If you have any issue at any time and you have reviewed the resources I provided and you cannot fix the issue,
please attend the Office Hours/Live Sessions so I can help you.
(7.) Include all these: (documentation of all your Math work and the .exe file) in OneDrive, create a
shareable link, and post the link in the Final Project Drafts forum of the course on Blackboard or send to me via email.
You may also upload them directly if you prefer.
I shall review and provide feedback.
(8.) When you are done with your project:
Make sure your executable file runs by itself outside the project folder
If it does run, include these three items: single executable file (that runs by itself outside the folder), the
Math documentation (Word document that has the Math part), and the entire project folder, into a folder,
zip the folder (.zip extension only) and submit it in the appropriate area of the Blackboard course.
If it does not run, please fix it.
If you cannot fix it, please attend the Office Hours/Live Sessions so I can help you.
NOTE: Any actual project submitted to me via email will not be graded.
The final project is designed to assess your expertise for developing a Windows Presentation Foundation (WPF)
desktop application of your Midterm Project using Extensible Application Markup Language (XAML).
(1.) It is expected that students who choose this option completed their Midterm Projects successfully.
(2.) When you are done with your project:
Make sure your executable file runs by itself outside the project folder
If it does run, include these three items: single executable file (that runs by itself outside the folder), the
Math documentation (Word document that has the Math part), and the entire project folder, into a folder,
zip the folder (.zip extension only) and submit it in the appropriate area of the Blackboard course.
If it does not run, please fix it.
If you cannot fix it, please attend the Office Hours/Live Sessions so I can help you.
(3.) The Reflection for the project is required.
Dear Students,
Greetings to you.
As you evaluate me and my teaching style on the Blackboard course, I ask that you consider these questions
in addition to the survey questions.
Thank you for giving me the opportunity to teach the course.
It was nice working with you.
I wish you the best in your academic profession.
Thank you!
Samuel Dominic Chukwuemeka (SamDom For Peace)
B.Eng., A.A.T, M.Ed., M.S
Working together for success
Classroom/Learning Environment: Blackboard course management system.
Course Assessments: Discussion Board (DB) assignments, Midterm Project, Final Project and the Final Exam
Direct forms of communication: live office hours/tutoring sessions, emails, comments to your DB posts and responses and
phone calls.
Indirect forms of communication: course announcements, websites (notes, videos, etc).
Course Contents
Please review the Course Description and Student Learning Outcomes
It is the first link in your course.
Those are the basic topics that KSU require that I teach.
(1.) Did I cover those topics: teaching and/or providing resources for those topics?
(2.) Did I cover other necessary topics that is relevant for you to succeed in your profession?
(3.) Did the assessments demonstrate the application of the topics?
(4.) Did the contents and assessments demonstrate important skills such as critical thinking, use of technology,
creativity, and organization among others?
Teaching and Learning
(5.) Did you acquire any knowledge from me?
(6.) Did you acquire sufficient knowledge, or more than sufficient knowledge from me?
(7.) Did you acquire any knowledge from any of your colleagues because of how the course was set up?
(8.) Did you acquire sufficient knowledge, or more than sufficient knowledge from any of your colleagues because of
the way the course was set up?
(9.) Did I provide multiple ways of completing each assessment?
In other words, were you given several options of completing each assessment?
(10.) Did I provide effective feedback for any of your assessments?
(11.) Did you acquire any knowledge based on that feedback?
(12.) Did the feedback help you improve in any way?
(13.) Did you have enough support to ensure the successful completion of the course?
Were your questions answered?
Did you have enough resources/learning aids?
(14.) Did I provide a safe and conducive environment for learning?
(15.) Was the Grading Method fair?
Pacing Guide
(16.) Were you given enough time to learn the contents?
(17.) Were you given enough time to complete the assessments?
Consider the fact that you were given two due dates for your Midterm Project, Final Project, and Final Exam; and that there
was no penalty for late work after the first due date.
Professionalism
(18.) In all our communication (both direct and indirect), did I act professionally?
(19.) In all our communication (both direct and indirect), did I use a respectful tone?
(20.) What do you like or dislike about our communication?
Personality
(21.) Based on your experience with me (taking the course with me and communicating with me among others), how
would you describe my person?
Do I give a lot of work?
Do I give a lot of explanations?
Do I have a lot of expectations for my students?
Do I really want you to learn?
Do I really want you to succeed?
Do I ask a lot of questions?
Do I answer questions with questions sometimes?
In those times, please note that it is a teaching technique.
It is never meant to disrespect you. I do not disrespect my students. I respect them.
It is a technique to guide you to review directions/concepts, and explain what you do not understand.
Would you take another course with me? Why or why not?
Did your views/perception about me affect you in completing this course successfully or unsuccessfully?
Need a programmer for personal/professional/commercial projects?
Look no further. Any of my available students (not just the ones listed here) can help.
Just head on to the Division of Student Affairs, Kent State University
or contact me here or via my school email address.
These are nice projects done by my students.
Some of them are Midterm Projects while some are Final Projects.
Because of FERPA (Federal Educational Rights and Privacy Act) laws, only the first names of my students are
written.
(1.) North Canton Water Rates by Melissa
As at today: $04/30/2021$, the verifiable website for this application is: Water Utility Services | North Canton, OH
(https://northcantonohio.gov/409/Water)
For a full breakdown of current Water Rates and regulations, consult Chapter 937 of the City's Codified Ordinances
(2.) $2020-2021$ Federal Tax: All Filing Options by Tyler
As at today: $05/10/2021$, the verifiable website for this application is: IRS.com (This is NOT IRS.gov)
(https://www.irs.com/articles/2020-federal-tax-rates-brackets-standard-deductions/)
(3.) City of Akron Current Water Rates by Ian
As at today: $04/08/2021$, the verifiable website for this application is: Water and Sewer Rates: City of Akron
(https://www.akronohio.gov/cms/site/dced0363af40e9b7/index.html)
Winter (Oct-May) Base Charge: $14.50 First 750 kWH: $0.100511 Over 750 kWH: $0.088511Alabama Power increased their rates
C# Documentation: Microsoft
C# Tutorial - Tutlane (Free)
C# Tutorial: W3schools.com (Free)
C# Tutorial - Tutorials Point (Free)
C# Developer Community
American Standard Code for Information Exchange (ASCII) Characters
Sorting Techniques and Algorithms
O'Reilly Online Learning
For Kent State University students, Select your Institution > Choose “Not Listed? Click here.”
Enter your Kent State University email address and click Let’s Go
LinkedIn Learning (Kent State University)
Microsoft Exams - ITExams (Free Past Questions and Answers But Requires Patience)
Tutorials, Exercises, and Solutions from W3Resource (Free)
C# Programming Exercises and Solutions from W3Resource (Free)
SoloLearn (Free)
C# Notes for Professionals: Stack Overflow Documentation
Wikibooks: C# Programming
Stack Overflow: Question and Answer Forum for Computer Science
Lynda.com from LinkedIn (Start for Free. Then, not free)
Codecademy (Start for Free. Then, not free)
Chukwuemeka, S.D (2016, April 30). Samuel Chukwuemeka Tutorials - Math, Science, and Technology.
Retrieved from https://www.samuelchukwuemeka.com
Farrell, J. (2018). Microsoft Visual C#: An Introduction to Object-Oriented Programming. Cengage Learning.
BillWagner. (2019). C# docs - get started, tutorials, reference. Microsoft.Com.
https://docs.microsoft.com/en-us/dotnet/csharp/
(2020). Goalkicker.Com. https://www.goalkicker.com/CSharpBook/CSharpNotesForProfessionals.pdf