0% found this document useful (0 votes)
410 views405 pages

C# - 3 in 1 - Beginner - S Guide+ Simple and Effective Tips and Tricks+ Advanced Guide To Learn C

Uploaded by

cblessi chimby
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
410 views405 pages

C# - 3 in 1 - Beginner - S Guide+ Simple and Effective Tips and Tricks+ Advanced Guide To Learn C

Uploaded by

cblessi chimby
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 405

© Copyright 2021 - All rights reserved.

This document is geared towards providing exact and reliable information in regards to the topic and issue covered. The
publication is sold with the idea that the publisher is not required to render accounting, officially permitted or otherwise qualified
services. If advice is necessary, legal or professional, a practiced individual in the profession should be ordered.
From a Declaration of Principles which was accepted and approved equally by a Committee of the American Bar Association and
a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic means or printed format.
Recording of this publication is strictly prohibited, and any storage of this document is not allowed unless with written
permission from the publisher. All rights reserved.
The information provided herein is Provinced to be truthful and consistent, in that any liability, in terms of inattention or
otherwise, by any usage or abuse of any policies, processes, or directions contained within is the solitary and utter responsibility
of the recipient reader. Under no circumstances will any legal responsibility or blame be held against the publisher for any
reparation, damages, or monetary loss due to the information herein, either directly or indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely and is universal as so. The presentation of the information is
without a contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without permission or backing by
the trademark owner. All trademarks and brands within this book are for clarifying purposes only and are owned by the owners
themselves, not affiliated with this document.
Table of Contents

C#
A Comprehensive Beginner's Guide
to Learn About the Realms of C# From A-Z
Introduction
Chapter 1 : Getting Started With C#.NET
CLR
Assembly
CIL
Chapter 2 : The Basic Elements of a Program
Chapter 3 : The Program Makes Decisions
Chapter 4 : Creating Loops
Loops That Start at Zero
Problems With the For Loop
Initialization of Variables in Loops
Problems With Variables in the Loops
Verify Changes in a Program
Guarantee the Execution of the While Loop
Nested Loops
Chapter 5 : The Functions and Methods
The Name of the Function
Problems in Declaring Functions
Name in Invocation
Be Careful With the Type of Return
Return’s Position in the Function
Parameter Order
Types of Parameters
To Know the Functions
Conclusion
Resources

C#
Simple and Effective Tips and Tricks
to Learn C# Programming Effectively
Introduction
Chapter One : What Is C#?
Community
Professional Version
Enterprise Version
Chapter Two : Getting Started With C#
Array Length
Array Loop
Item Removal
List Creation
Concatenation
Chapter Three : C# Conditionals
Chapter Four : Interactive Programming
Chapter Five : C# Loops
Chapter Six : C# Methods
Chapter Seven : Object-Oriented Programming
Chapter Eight : C# Classes Explained Further
Chapter Nine : Writing Secure Code
Spoofing
Tampering
Repudiation
Information Disclosure
Denial of Service
Privilege
Conclusion
References

C#
Advanced Guide to Learn C# Programming Effectively
Introduction
Chapter One : Getting Familiar with the Foundations of C#
Defining Classes
Using a Class in a Console Application
Printing a Statement in a Console Application
Performing a ‘Read’ on the Command Prompt
Using Fields and Properties
Defining a Field
Defining Properties
Read-Only Properties
Write-Only Properties
Indexed Properties
Using an Instance of a Class
Defining an Interface
Implementing an Interface
Inheritance
Encapsulation and Aggregation
Polymorphism
Access, Class, and Member Modifiers
Chapter Two : Working with the Assembly Viewer and UserControls
The ‘using’ Statement
Working with the Assembly Using Reflection
The ‘Broadcaster’ Class
Using the ‘Broadcaster’ Class
Defining the Interface for the ‘Broadcaster’ Class
Implementing the ‘StatusBar’ Form Control
Implementing the ‘MainMenu’ Form Control
Implementing the ‘OpenFileDialog’ Form Control
Making the Graphical Interface of the UserControl
Promoting Events in Constituent Controls
Other Choice for Member Promotion
Chapter Three : Working with Video Kiosk Using C#
GDI+ Namespaces
PlayControl
Background
Buttons and Custom Controls
Conditional Logic and using Arrays
Using Graphics Objects
Paint Event Handler
Overloading OnPaint
Invalidating a Control
Pens
Defining Tracker Control
SetStyle
ControlPaint
Drawing a 3D Border
Drawing a Button Control
Graphics.DrawImage
Using TimeSpan to Tell Time
Formatting Strings
Adding Controls to a Toolbox
Catching and Handling Exceptions
Making a TODO List
The Process Class
Chapter Four : Personalizing the Visual Studio .NET Framework Environment
Using IDTWizard
Pass-By Referencing
Testing the Wizard
Creating a New Template from a Pre-Existing Template
Adding Files to the Wizard Library Template
Modifying default.js
Modifying common.js
The Wizard Launch File
Creating a VSDir File
The Common Environment Model
Writing Code, using Macros
User Interface Strategies:
Dialog Form Strategies
Implementing the Wizard
Registering Wizards
Testing the Wizard using a Macro
Running the Wizard from the Command Window
Returning to JScript
Using the regasm Utility
Conclusion
References
C#
A Comprehensive Beginner's Guide
to Learn About the Realms of
C# From A-Z

BENJAMIN SMITH
Introduction

The ease with which you have access to a computer today has led people to use them in many
activities, using software that performs specific tasks. When the computer is required to carry out
other types of actions, and the available programs do not, it is necessary to tell it in its language
how it should act, and for this, the programming languages are used.
Programming languages try to resemble our own way of expressing ourselves. For this, they
have their own syntax and semantics, as well as symbols that allow us to tell the computer what
processes and what data to handle, how to store them, what actions to perform with them and
how to present them to the user. For this reason, it is important to have a methodology that
allows learning correct and effective habits to solve problems, which, when subdivided for better
understanding, will facilitate their resolution.
Once the problem has been understood, a sequence of steps to be carried out is constructed,
better known as an algorithm, which will allow testing whether the logic is correct and whether
the results that will be obtained will be adequate. The potential of the current programming
languages is enormous because it allows for the automation of very different types of activities.
As such, this reduces the time that is invested in doing it manually and, if you learn to use them
correctly, it will be easier for the users who use such programs.
Learning to program is a task that requires practice and patience, but it is also a fascinating
activity. If you also have an excellent book and the necessary consistency, the results will be
excellent. Congratulations on this new challenge that is about to begin!
C # or C Sharp is a programming language that is included in the .NET Platform and runs in the
Common Language Runtime (CLR). The first language of importance to the CLR is C #, much
of what the .NET Platform supports is written in C #.
C # is derived from C and C ++, and it is modern, simple, and entirely object-oriented. It
simplifies and modernizes C ++ in the areas of classes, namespaces, method overloading, and
exception handling. C ++ complexity has been removed to make it easier to use and less error-
prone.
Many books, when going through the chapters, mention all the details of the language, along
with its basic principles. This ends up creating a lot of confusion, especially because the student
cannot differentiate exactly what is essential to learn in the beginning, from what can be left to
study later.
Whether or not an abstract class should have at least one abstract method, if it only accepts
Boolean arguments and all the details about inner classes, it really shouldn't be a concern for one
whose primary goal is to learn C #. This type of information will be acquired over time and is not
necessary at the beginning.
In this course, we separate this information into special boxes, as they are extra information. Or,
we just quote in some exercise and leave it to the reader to look for additional information, if it is
of interest.
Finally, there is still something to mention about the practice, which must be taken seriously:
practice is very important. We recommend students to study each section of the book and
practice a lot of code and variations.
Chapter 1
Getting Started With C#.NET

This book is intended for all those who want to learn the C # programming language and have
basic programming knowledge or have no previous experience programming computers. The
focus of the book is to guide the learning of C # (an object-oriented) language step by step. In the
first chapters, we will take a structured philosophy to make learning even easier for all of us.

Brief History of Windows Programming


A few years ago, the only way you could program for Windows was to make use of a C or C ++
compiler and a Windows API. The API is a large collection of related functions, which allow us
to communicate with the operating system. Through the Win32 API, windows, buttons, and
other elements were programmed.
The problem with this type of programming is that the Win32 API is really complex and huge.
With thousands of functions inside, few programmers could know it all. But the complexity was
not only in the number of functions but also in the syntax and the way it is programmed.
To facilitate the programming of applications for Windows, different options appear; the purpose
of these attempts was to be able to make the applications without having to go through the
complexity of Win32. One of these attempts was known as OWL (Object Windows Library);
However, MFC (Microsoft Foundation Class) Library, created by Microsoft, was more
successful.
MFC is a set of classes that involves Win32 and facilitates its programming. With MFC, the
most common processes are grouped in functions so that with a simple call to an MFC function,
you can do a certain task, for which before we needed at least ten calls in Win32 and many
parameters. However, Win32 is under MFC; MFC programming simplifies things a lot, but
many programmers who came from the structured programming paradigm did not feel
comfortable with it.
Another option that emerged is Visual Basic; this language achieved great popularity among the
programmers. Visual Basic also works above Win32 but bases its syntax on the old Basic
language. It is very easy to learn, and one of the features that made it very popular was the ease
with which you could create user interfaces and database connectivity. But until before the .NET
version, this language had certain limitations since it was not possible to carry out object-
oriented programming with it.
Another language that emerges, but with its own framework, is JAVA; its main advantage is to
be multiplatform. One of its characteristics is the use of a runtime, instead of running directly in
the microprocessor the application runs in a program called runtime and this is responsible for
executing the code in the corresponding microprocessor. If you have the runtime for Windows,
the JAVA program runs without a problem.
When we wanted to run a program, it was necessary to compile it. Each language had its own
compiler, so it was not easy to share C++ code with Visual Basic code because translating
between languages was difficult. To share code between languages, a model known as the
Component Object Model (COM) was created. This model allows us to create binary
components, and this means that it is possible to program a component in Visual Basic, and a
C++ programmer can take it and make use of it. This is because the component is already
compiled code and not source code in the source language; COM programming also had its
complexities, so the Active Template Library (ATL) was created to help in its development.
With all this, the time comes when it is necessary to order, facilitate, and organize the
development of applications for Windows, with this philosophy .NET emerged.

Discover .NET
The .NET Framework is a solution to all the problems involved in the development of
applications, providing great benefits not only to the developer but also to the development
process. First of all, .NET allows us to work with existing code; we can use COM components,
and even, in the situation where we need to use the Windows API. When the .NET program is
ready, it is much easier to install on the client's computer than traditional applications since it has
a strong integration between languages.
A C# programmer can easily understand the code of a Visual Basic .NET programmer, and both
can program in the language they are most comfortable with. This is because all the languages
that make use of .NET share the .NET libraries, so it does not matter in which language we
program in, we can recognize it in any language. Next, we will know the different components of
.NET: Common Language Runtime (CLR), Assembly, and Common Intermediate Language
(CIL).
CLR
The first component of .NET that we will know is the Common Language Runtime, also called
CLR. This is an execution program common to all languages. This program is in charge of
reading the code generated by the compiler and starts its execution. It does not matter if the
program was created with C#, Visual Basic .NET, or some other .NET language, the CLR reads
it and executes it.
Assembly
When we have a program written in a .NET language, and we compile it, the assembly is
generated. The assembly contains CIL in the compiled program and also the information about
all the types that are used in the program.
CIL
The .NET programs are not compiled directly into compiler assembly code; instead, they are
compiled into an intermediate language known as CIL. This language is read and executed by the
runtime. The use of CIL and runtime is what gives .NET its great flexibility and its ability to be
multiplatform.
The Framework of .NET has Common Language Specifications or CLS. These specifications are
the guidelines that any language that you want to use .NET must meet to be able to work with the
runtime. One advantage of this is that if our code complies with the CLS, we can have
interoperability with other languages, for example, it is possible to create a library in C #, and a
Visual Basic .NET programmer can use it without any problem.
One of the most important points of these guidelines is the CTS or Common Type System. In
programming languages, when we want to save information, it is placed in a variable, the
variable will have a type depending on the information to save, for example, the type can be to
save an integer, the other to store a number with decimals and the other to save a phrase or word.
The problem with this is that each language store information differently. Some languages store
integers with 16-bit memory and other with 32-bit; even some languages, such as C and C++, do
not have a type for storing strings or phrases.
To solve this, the .NET Framework defines through CTS how the types will work in their
environment. Any language that works with .NET must use the types as outlined in the CTS.
Now that we know the basic concepts, and we can see how all this comes together.

How to Create a .NET Application


We can create a .NET application using a programming language. For this purpose, it will be C#;
with this programming language, we can create the source code of the program (instructions that
tell the program what to do).
When we have finished with our source code, then we have to use the compiler. The compiler
takes the source code and creates an assembly for us. This assembly will have the equivalent of
our code, but written in CIL, leading us to another advantage of .NET - the compiler can
optimize our code for the platform where we are going to use the program, that means the same
program can be optimized for a mobile device, a normal PC or a server, without making any
changes to it.
The .NET Framework can be run on many platforms, not just on Windows. This means that we
can program on a particular platform, and if another platform has the runtime, our program will
run without any problem. A .NET program developed in Windows can be executed in Linux, as
long as it has the corresponding runtime.
When we want to invoke the program, then the runtime gets into the action, reads the assembly,
and creates the entire environment for us. The runtime starts reading the CIL instructions from
the assembly and compiles them as it reads them for the microprocessor of the computer on
which the program is running; this is known as JIT or just-in-time compilation. In this way, the
program advances in execution, and it is compiled; all this occurs transparently for the user.
The JIT compiler is also known as Jitter. It is part of the runtime and is very efficient if the
program needs to re-run a code that has already been compiled, the Jitter instead of recompiling,
runs what has already been compiled, thus improving performance and response times for the
user.
For the programs that are running, the .NET Framework provides the services of memory
management and garbage collection. In unmanaged languages such as C and C++, the
programmer is responsible for memory management. In large programs, this can be a
complicated task, which can lead to errors during program execution. Fortunately, managed
languages like C# have a model in which we, as programmers, no longer need to be responsible
for memory usage. The garbage collector is in charge of removing all objects that are no longer
needed when an object is no longer use the collector takes it and removes it. This frees up
memory and resources.
The garbage collector works automatically for us and helps to eliminate all the memory and
resource management that was necessary for Win32. In some special cases, like files, databases,
or network connections are unmanaged resources. For these cases, we must explicitly indicate
when they need to be destroyed.

How to Get a C# Compiler


There are several compiler options for C#, to make the learning easy and smooth for the
beginners; in this book, we will use the C# 4.0 version that comes with Visual Studio 2010. Still,
it is also possible to use a later or older versions. Most of the examples should be able to be
compiled and run without any problem.
In case we cannot get the professional version of Visual Studio 2019, a better option is the
Community version formerly known as the Express version. This version is free and can be
downloaded directly from the Internet; all you need to do is go through a small survey. To
download the C # Visual Studio compiler (Community Version) completely free, you can access
the Microsoft portal here .
Once we have downloaded the compiler, we can proceed to carry out the installation; this task is
very similar to installing any other Windows program, but do not forget to register it within 30
days.

The Development Environment


Once the installation is finished, we can start the program by selecting it from the Windows Start
menu. You will see a window that shows the user interface of the application.
Basically, the interface is divided into two parts: on the left, we have the search bar named Open
recent where we can find links to our most recent projects or solutions by entering keywords.
And on the right side of the home page, we will see the options of Create a new project , Open
a local folder , Open a project or solution, and access to code repositories titled Clone or
check out code. We can also receive announcements and news about software development
using C # in this same part of the interface, but as we move through different pages, we will have
the editing zones. These editing areas will allow us to edit the program code, edit the user
interface, icons and other resources.
Editing the program code is a very simple activity that should not make us worry if we know
how to use any type of text editor such as Microsoft Word or Windows Notepad, and then we
can edit the program code. The other editors are also quite user-friendly, but we will not need
them to perform the examples shown in this book.
On the right side, we have a window that is known as Solution Explorer, in this same area other
windows will appear that give us information about the project we are developing. We will see
the details shown by some of these windows a little later in this book.

At the bottom, we find another window; in this area, there are usually the sections that the
compiler will use to communicate with us. For example, we will see the window that indicates
the errors that our program has; at the top of the window, we will see the menus and the toolbars.
If, for any reason, we close the source code editor or it does not appear in our user interface, the
easiest way to find it is through the Solution Explorer. Simply go to the document that represents
your source code and double click on it, the window with the source code editor will appear.

How to Create Our First Application


To become more familiar with C# Visual Studio Express, it is best to create the first project and
work on it. We will generate a small program that sends us a message in the console, and then
we will add other elements so that we can explore the different windows of the user interface.
There are mainly two ways to create a new project in Visual Studio 2019. The first one is simply
clicking on Create a New Project from the bottom right part of the main visual studio interface.
Then type console in the search box and choose the Console App (.NET Framework) option and
click the Next button as shown below.
Then configure your new project with its Name and Location, save and hit the create button.
All set, the Visual Studio will instantly create a new project for you.
Alternatively, to create a project, we can select the File menu, and after that, we have to click on
the option New Project as shown in the image below, this way we will see a dialog box that
shows some related options.
In the right part of the dialog box, the different types of projects that we can create are listed; for
this example, we must select the one indicated by the console application and click the next
button.
Note: If, for any reason, we close the source code editor or it does not appear in our user
interface, the easiest way to find it is through the Solution Explorer. Simply go to the document
that represents your source code and double click on it, the window with the source code editor
will appear.
On the left side, we will write the name of our project, which in this case, will be MyProject.
Each new project we will create will have its own name; then, we will simply press the Create
button.
In a few seconds, C # Express creates the project for us. Visual Studio and the Community
version make use of solutions and projects, a solution can have several projects, and for example,
Office has different products such as Word, Excel, and PowerPoint. The office is a solution, and
each product is a project. The project can be a stand-alone program or a library and can have one
or more documents, and these documents can be the source code and additional resources.
We can see that our user interface has changed a bit, the windows already show us information,
and we can also see that the skeleton for our program is shown in the editing area.

The Solution Explorer shows us the information about the solution in a logical way if we
observe, it is like a small tree. At the root, we find the solution; each project we have in that
solution will be a branch, each project, in turn, will also have its divisions. In our case, we see
three elements; two of those elements are folders; in one, we keep the properties of the project,
and in the other, the references (during this book, we will not use these folders). The fourth
element is a document called Program.cs, this represents the document where we save the source
code of our application. We see that the extension of the C# programs is .CS.
In the editing area, we can see that we have a skeleton so that, from there, we can create our own
program. To understand what we have, there is necessary to know a concept: namespace. The
namespace is a logical grouping; for example, all the code that we can have related to
mathematics can be grouped inside the namespace of Math. Another use that namespace has is to
solve conflicts with names, for example, let's suppose that we have a massive project and several
programmers working on it. Two or more programmers could have created a method that had the
same name; this generates a conflict since the program could not know which version to use. The
way to solve this is that each programmer has its own namespace and refers to the corresponding
namespace according to the version we want to use.
The .NET Framework provides us with various namespaces where we have thousands of classes
and methods already created for our use. When we want to use the resources found in a
namespace programmed by other programmers or by us, we must make use of a C # command
known as using.
As we can see at the top of the code, we have several using references to the namespaces that our
application needs; if we needed to add more namespaces, we would do it in this section.
Below is defining the proper namespace of our project; this is done as follows:
namespace MyProject
{
}
The namespace we are creating is called MyProject. As we can see, the namespace uses {} as
delimiters; this is known as a code block, and everything that is placed between {} will belong to
the namespace. This is where it will be necessary to write the code corresponding to our
application.
Inside the code block, we find the declaration of a class, C# is an object-oriented language, and
that is why it needs us to declare a class for our application. The class has its own block of code,
and in our application, it will be called Program. The concept of the class will be covered in
Chapter 10 of this book.
All programs need a starting point, a place that indicates where the program execution starts, in
C#, as in other languages, the starting point is the Main() function; this function also has its own
code block. Within this function, we will generally place the main code of our application,
although it is possible to have more functions or methods and classes. The parts and
characteristics of the functions are seen in Chapter 5 of this book.
Now it is time to create our first application. We are going to modify the function code, as shown
below. When we are adding the statement inside Main(), we must notice that it happens
immediately after the point is placed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main (string [] args)
{
Console.WriteLine ("Hello World!");
}
}
}
If we can manage to observe during writing the code when you will write the word Console and
then insert the dot, a box will appear listing different elements. This box is called autocomplete
and allows us to work quickly and reduce the number of syntax errors. The autocomplete box
shows us a suggestion of the word, command, variable, etc. that could be used next. If we want,
we can select it from that list, and it will write for us; as we progress and become familiar with
C# programming, we will see that this feature is so helpful.
In our example, we have placed a statement that will write the Hello World message on the
console. This is a very simple program, but it will allow us to learn how to compile the
application and see the program running.

To Compile the Application


Once we finish writing our program, we can carry out the compilation, as we learned earlier; this
will generate the assembly that will then be used by the runtime when executed.
To compile the application, we must select the Build menu and then Build Solution or simply
pressing by the F6 button. The compiler will start working, and in the status bar, we will see that
our solution has been compiled successfully.

To Run the Application


Once the compilation has been successful, we can run our program and see how it works. For
this, we have two options: run with debugging and execute without debugging. In the Express
version, only the execution with debugging appears, but we can use the execution without
debugging with the keys CTRL+F5 or adding it using the tools menu.
The debugger is a program that helps us correct errors at runtime and also logic errors. Preferably
we should use the execution without the debugger and make use of the execution with debugging
only when we really need it. Now we will run our application; for this, we press the CTRL + F5
keys.
When the program is executed, a window appears, we call it console, and it shows the execution
of the program. In this way, we can read the message that we had placed in our example.
Since this is a starter book for programming with C#, so we will run all programs on the console.
Once you understand the main concepts, you can learn how to program shapes, forms, and
graphical interfaces in C#. This type of programming is not difficult, but it requires basic
knowledge of object-oriented programming.

How to Detect Errors in a Program


Sometimes we may write the program incorrectly; when this happens, the application cannot be
compiled or executed; if this happens, we must change what is wrong.
Let's write an error intentionally so that we can see how the compiler behaves.
In the program, we have changed ‘Console’ to ‘Consoli’ and reordered ‘namespace’
‘HelloWorld,’ this will cause an error; now, we can try to compile again and see what happens.

As we already know, the window that appears at the bottom of our user interface is used by the
compiler to communicate; we see that a window appears that gives us a list of errors. In the next
book, we will learn how to use it; for now, we simply need to know that it is always necessary to
solve the first problem in the list and that we can go directly to the error by double-clicking on it.

The Class View


Now we are going to check the class view. In this view, we can get information about the
solution we are creating, but unlike Solution Explorer, the information is arranged logically.
With this view, we can quickly find the namespaces of our solution and within them the classes
they contain; if we wish, we can see the methods that are in each class. This view not only allows
us to observe the logical information but also gives us the possibility to quickly navigate in our
code.
In the Community version, there is no previously configured option, so it is necessary to add the
command to the View menu.
To show the class view, we must go to the View menu and then select Class View or simply
pressing Ctrl + W, C a window will appear in our user interface.

The class view window is divided into two sections; the upper section shows the logical and
hierarchical relationship of the elements while the lower section shows the methods that make up
a particular class.
At the root of the tree, we find the project; it will contain the necessary references and the
namespaces of HelloWorld. If we had more namespaces, they would appear there, when opening
the HelloWorld namespace we find the classes that are unclaimed within it. In this case, we only
have the Program class; if we select it, we will see that at the bottom, the elements that are
declared inside are shown. In our example, we have the Main () method.
If at this time, we double click on any of the methods, we will automatically go to the code
where it is defined. Because our program is very small, we may not see the advantage of this, but
in programs with thousands of lines of code, being able to navigate quickly is a great advantage.

Configuring Compiler Menus


To add the options we need in the menus, we must follow a series of very simple steps. First, go
to the Tools menu and select the Customize option.
A dialog box appears, in which we must select Commands; in this section, we can choose the
menu to which we want to add a command, for example, the View menu.
The current menu commands are listed, we click on the area where we want the new command to
be inserted and press the Add Command button. With this, a new dialog box appears that shows
all the possible commands that we can add classified into categories.
In the categories we select View, and in the Class View commands, this command is the one that
allows us to have the class view. The Start Without Debugging command is in the Debug
category.
Up to this point, we have analyzed the most important basic concepts needed to understand the
operation of .NET. From the next chapter, we will begin with our learning of programming and
the C# language.
Chapter 2
The Basic Elements of a Program

The time has come to learn how to develop computer programs. Some people think that
programming software is complex and difficult; however, this is not true or was a long time ago.
To be programmers, we only need to know a programming language and the necessary
techniques to develop programs. Throughout this chapter, we will learn both.

The Programming Languages


When we want to communicate with a person, we use a common language to understand each
other. With this book, we are communicating through the English language. But if a person from
another country where English is not spoken comes to visit us, then we would have a problem.
The solution to this problem is very simple: we need to learn the language of this person to
communicate with him. The same thing happens with the computer if we want to program it, it is
necessary to communicate with it, and the correct way to do it is by speaking its language. Then
we can say that the language of the computer is known as the programming language, and the
programming language we will learn here is C# or C Sharp. This language is simple and
powerful at the same time.
Once we know the programming language, then the computer will understand what we want it to
do. Programming languages have existed for many years and are of different types. Some have
evolved, and new languages such as C# have emerged. Other languages are specialized for
certain tasks, and many others have become extinct or obsolete.

The Computer Programs


All or most of us know how to bake a cake, and in fact, this is an excellent example of how to
make a computer program. When we want to bake a cake, the first thing we need is the
ingredients. If any are missing, then we won't have a sweet cake. Once we have prepared or
collected our ingredients, we follow the recipe to the letter. It tells us step by step what to do.
But what if we don't follow the steps of the recipe, what if we put the ingredients in the oven first
and then stir them and the result is a cake? The answer to these questions is clear: the result is not
a cake. From this, we deduce that to achieve something, and we need a series of steps. But it is
also necessary to follow them in the right order, and we call this series of steps a recipe.
Note: An error you may have when you start programming computers with C# is forgetting to
place a ; (semicolon) at the end of the sentence. If our program has some error and everything
seems to be okay, we surely forgot some semicolon. It is good to recognize these types of errors
since it allows us to reduce the necessary correction time.
Anyone can think of an activity and mention the list of steps and the order in which they should
be carried out. We can easily make the list of steps to change the tire of the car or to feed the fish
in the aquarium. With this, we see that we will not find any problem to list the steps of any
activity we do.
Now, we probably ask ourselves: what does this have to do with computer programming? And
the answer is simple. Anyone who can make a list of steps can program a computer. The
computer program is nothing more than a list of the steps that the computer has to follow to do
some activity. We call this list of steps an algorithm. An algorithm is the steps necessary to act.
An important feature of the algorithm is that it has a starting point and an endpoint, which
indicates that the steps are carried out sequentially, one after the other. The algorithm would be
equivalent to the cake recipe, and the necessary ingredients will usually be the data or
information we will use.
Let's run a little program to see how this would work. To do this, we create a project, as we saw
in Chapter 1. Our program will show the steps to make a cake or a pie. We place the following
code in our program and see how it corresponds to what we have learned.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BaseApplication
{
class Program
{
This is the main function of the program. Here the application starts.
static void Main(string[] args)
{
Console.WriteLine(“1 - Preheat the oven”);
Console.WriteLine(“2 - Whisk margarine with sugar”);
Console.WriteLine("3- Add eggs");
Console.WriteLine(“4 - Sift flour”);
Console.WriteLine("5- Add to mix and milk");
Console.WriteLine(“6 - Bake for 40 minutes”) ;
Console.WriteLine(“7 - Decorate and eat”);
}
}
}
The functions are sections of the program in which we can have specialized code. The Main()
function is invoked by the operating system when we want our program to start. It is the only
must-have function that all the programs we develop.
C # is an object-oriented language and needs us to define a class to create a program. At this
time, we will not see the classes, but we will return to them in a later chapter. The first thing to
find is a function called main(), which is very important, as we saw in Chapter 1.
We already know that algorithms need a beginning and an end. In our program, the point where
it always starts is the Main() function. This function indicates the starting point of our program,
and here we will place the steps that our program must follow in the right order.
To indicate all the steps that belong to Main(), we need to place them in their code block. A code
block is defined between braces { }. Anything in that code block belongs to Main(), anything
outside it does not.
It is important to note that the class also has a code block, and Main() is inside it. Similarly, the
namespace also has its own code block, and the class is inside it, although for now, we'll just
focus on the Main() code block.
A common error when creating code blocks forgets to close them. As a recommendation, once
we open a code block with {, we should immediately put the closure with} and then program its
content. In this way, we will not forget to close it. Inside Main(), we find the steps of our
algorithm. At this moment, they may seem strange to us, but we will learn what they mean. We
have to remember that we must learn the computer language and these are one of its first
sentences.
What we find inside the Main () function is a series of statements. The sentences allow us to
place instructions that our program can execute, which are used to display a message on the
screen. The message that we want to display on the screen is shown when invoking the
WriteLine () method. The methods are similar to the functions; they exist inside the classes and
allow us to make use of the internal functionalities. This method belongs to the Console class,
and in that class, we will find everything necessary so that we can work with the console, either
by placing messages or reading the information provided by the user. Since WriteLine () belongs
to Console when we want to use it, we must write:
Console.WriteLine ("Hello");
WriteLine () needs some information to work. This information is the message we want to show.
Methods are the passed information they need to work through their parameters. The necessary
parameters are co-located in parentheses (). WriteLine () will need a parameter of type string.
A string is a collection of characters, that is, letters, numbers, and signs. The chain is delimited
with double quotes ". In the example, the message we want to display is: Hello. So we pass the
string type parameter, "Hello."
Statements end with a semicolon (;). This is important, and we should not forget it since this
particular character is recognized by C # to indicate that the sentence written up to there has
ended.
In each of the sentences invoked so far by our program, we have sent one message after another
with each step necessary to make our cake. Finally, it only remains that we run the written
program and see the result that appears on the screen.
We can see that the execution has shown the messages in the order in which we have put them.
Now we can do a little experiment. We will change the order of the sentences, and we will
observe what happens. The program will be as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{

static void Main(string[] args)


{
Console.WriteLine("1 - Preheat the oven");
Console.WriteLine("2 - Whisk margarine with sugar");
Console.WriteLine("6 - Bake for 40 minutes") ;
Console.WriteLine("5- Add to mix and milk");
Console.WriteLine("7 - Decorate and eat");
Console.WriteLine("3- Add eggs");
Console.WriteLine("4 - Sift flour");
}
}
}
Let's run it and see what happens.
We can see that when it is executed, the statements are executed in the same order as they are in
the program code; they are not executed as we know they should be executed. This point is
important since it shows us that putting the statements of the program in the correct order of
execution is the responsibility of the programmer. The computer cannot read our minds and
know what we really want; it only faithfully executes the sentences in the order in which we put
them. If in real life we first bake and then whisk, we can't expect to get a pie or a cake.
Therefore, if we do not put the statements of the program in the proper order on the computer,
we cannot expect to have a functional program.
When a method is invoked, it is necessary not only to put its name but also to put the
parentheses. These should be set even when the method does not need parameters. Do not forget
to use the closing parenthesis). If we forget to put the parentheses, the compiler will mark errors,
and we will not be able to execute the program.

Errors in the Programs


An important part of programming is in recognizing the errors we may have to fix to allow the
program to work properly. We can have two types of errors: syntax errors and logic errors.
Syntax errors are easy to fix and are because we write the program's sentences in the wrong
order. These errors are shown when the program is compiled, and that way, they can be easily
looked up to fix them. Logic errors are the consequence of the fact that we have created our
algorithm incorrectly, and even if all the statements are correct, the program does not carry out
what we want. These errors are more difficult to fix, and the best way to avoid them is through
an adequate previous analysis of the problem to be solved. Later we will learn how to carry out
this analysis.
Let's start recognizing the syntax errors and messages that the compiler gives when we have
them. Recognizing these messages and how they were caused will allow us to resolve them in
the future quickly. To do this, we will start doing some experiments. In our program code, in any
of the statements, we remove the semicolon at the end and then compile it to see what happens.
Since we have removed the semicolon, we have a syntax error, and the compiler tells us that the
program has not compiled successfully.
Inside our compiler, the error list window will be displayed. The errors found by the compiler are
shown in this window. It is always necessary to solve the problem at the top of the list and not
the last one, because many times, by solving the first one, two others that were dragging your
problem are solved. The message that we see indicates that it was a semicolon, as in the next
figure.

Sometimes it happens that we forget to put the string in quotation marks or that only the
beginning quotation mark has been placed. It is important not to forget to always put the strings
between the two quotes. If we don't do it this way, the compiler can't find the string correctly or
where it ends, and the statement will give us a compile error.
The error list gives us a description of the error and also allows us to see the line number where
the error is located. An easy way to get to it is to simply double-click on the error description so
that the C# environment will take you directly to where the error is. Let's put the semicolon back
where it was in the beginning and compile. This time, the program can be compiled and executed
without problems, based on the correction that we have made in advance. The error has been
fixed. The solution provided by C# to correct errors is practical and simple to implement.
Now let's experience another bug. In the first sentence we delete the closing parenthesis and then
compile to see what happens:

Let's correct the error and recompile it. Everything must be okay. But what we will do now is
delete the closing quotation marks from the string in the first statement. This error presents us
with a more interesting scenario, and it is convenient for us to understand what is happening.
Let's compile the program and look at our list of errors. This will be much more extensive than
the previous ones:
Something interesting has happened here, even though we have only created one error: in the list
of errors, there are three errors. This is because one error can cause other errors in the following
code. By not closing the string, the compiler doesn't know where the statement ends and believes
that the closing parenthesis and semicolon are part of the string. That's why it also shows us that
the parenthesis and semicolon are missing.
Since errors can be chained, as in this example, we always need to fix the error that comes first.
If we were to try to fix the semicolon error first, it would not be obvious to see what the error is
in that line, since we would see that the semicolon itself is written.
Sometimes it happens that our program shows many errors, but when we fix the first error, most
of them disappear. This is due to factors similar to those we have just discussed above.
A common mistake that beginners make when naming their variables is that they forget how they
named the variable and write it sometimes in lower case and sometimes in upper case. This leads
to errors in logic or syntax. To avoid this, we can use a table that contains information about the
variables of our program.

The Difference Between the Write () and WriteLine () Methods


We have seen that the WriteLine () method allows us to display a message in the console, but
there is a similar method called Write (). The difference is very simple. After writing the
WriteLine () message, it inserts a line break, so the next thing to write appears on the next line.
On the other hand, the Write() method does not carry out any line breaks, and the next thing that
is written will be on the same line. Let's see all this in the following example:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
static void Main(string[] args)
{
Console.Write("Message 1");
Console.Write("Message 2");
Console.WriteLine("Message 3");
Console.WriteLine("Message 4");
Console.Write("Message 5");
}
}
}

When executing it, in effect, we see that after using Write (), the next element that is written is
placed in the same line, but when using WriteLine (), the next element appears in the following
line. This is a clear example of what was explained previously.

The Variables
Computers not only write messages on the screen, but they also have to do useful things. To do
them, they need information. The information must be stored and manipulated in some way.
When we want to store something in everyday life, we can use boxes, so anything we want to
store can be placed in a cardboard box, for example. However, the size of the box will depend on
what we want to store. A pair of shoes can fit into a small box, but we cannot put a television in
that box. If we start storing a lot of things in boxes, we will soon have too many, and it will be
difficult to find what we have stored. So one way to deal with this is through labels, we can label
each box with the content, and in this way, we can quickly find what we are looking for.
The variables in the computer work similarly to our storage boxes. We can imagine them as
small boxes that exist in computer memory, and their size will depend on the information they
are supposed to store. This is known as the variable type. To access that box or variable, we give
it a name that would be the label with which we identify it.
To make use of a variable, the first thing we have to do is declare it. The declaration of this is
something very simple. As a first step, we have to assign the type and then the name. The
variables in C# must be named according to some simple recommendations:
The names of the variables must begin with a letter.
It is possible to place numbers in the variable names, but not to start the name with
them.
The names of the variables cannot bear any signs except for the underscore _ .
Variables cannot have accents in their names.

When we name the variables, we have to take into account that C# is case sensitive, so a variable
called cost is not the same as another variable called COST or another one called Cost.
It is recommended to name the variables with names that refer to the information they will keep.
If we get used to doing this since we started programming, we will avoid many problems in the
future, and it will be much easier to fix our programs when they have errors.
Let's look at an example of how we can declare a variable that stores integer numerical values.
The type that stores these values is known as int.
int cost;
We see that at the end of the sentence, we have placed the semicolon. If we need to declare more
variables, we can do it in the following way:
int cost;
int value;
int tax
But it is also possible to declare the variables on a single line. For this, we simply separate the
names of the variables with commas. Do not forget to put the semicolon at the end of the
sentence.
int cost, value, tax;

Type Information You Store


bool Is a Boolean variable, i.e., you can only save the true or false values
(True or false) in terms of C #.
byte You can save a byte of information. This equates to a positive integer
value between 0 and 255.
sbyte Save a signed byte of information. We can save an integer value
from -128 to 127.
char You can save a Unicode character type.
decimal This type can save a numeric value with decimals. Its range is from ±
1.0? 10? 28
up to ± 7.9? 1028.
double We also can store numeric values that have decimals. The approximate
range
It is from ± 5.0? 10? 324 to ± 1.7? 10,308.
bool Is a Boolean variable, i.e., you can only save the true or false values
(True or false) in terms of C #.
byte You can save a byte of information. This equates to a positive integer
value between 0 and 255.
sbyte Save a signed byte of information. We can save an integer value
from -128 to 127.
char You can save a Unicode character type.
decimal This type can save a numeric value with decimals. Its range is from ±
1.0? 10? 28
up to ± 7.9? 1028.
double We also can store numeric values that have decimals. The approximate
range
It is from ± 5.0? 10? 324 to ± 1.7? 10,308.

It is important to know the types and information that can be saved, as this will allow us to save
the necessary information and use the least amount of memory. We can learn the ranges of the
types or print a table and have them at hand. With practice, we will be able to use the types
without having to check the ranges regularly.
An important point to note is that the assignment is always carried out from right to left. This
means that the value to the right of the equal sign is assigned to the variable to the left of the
equal sign. If we don't do it this way, the value cannot be assigned or will be assigned to the
wrong variable.
Once we have declared the variable, we must initialize it. Initializing a variable is assigning a
value to it for the first time. This allows us to give it an initial value that can be useful in the
execution of our program (not only can we assign a variable a fixed value, but it can also be from
a text entered by the user or from the registration of a database).
To assign a value to a variable, either during initialization or during the course of the program,
we use an assignment operator, the equal sign. Let's see below an example of how to assign
values:
cost = 50;
value = 75;
tax = 10;
In this case, the cost variable stores the value of 50, the value variable stores 75, and the tax
variable stores the value 10.
An invalid assignment would be as follows:
50 = cost;
In this case, nothing is assigned to the cost variable. The variable that receives the value is
always placed to the left of the equal sign.
If we need it, it is possible to initialize the variable when declaring it. This is very comfortable,
and if we do so, we avoid forgetting the initialization of the variable. To do this, we place the
type of the variable followed by the name to be used in the variable, and immediately with the
assignment operator, we place the value.
int cost = 50;

Comments on the Program


Computer programs can be extensive, so it is necessary to put code comments in the program.
Comments serve to document parts of the program, explain what a certain part of the code does,
or simply place a reminder.
We can make single-line comments, which are placed using the double bar // followed by the
comment text. Text found after the double slash // and up to the end of the line is ignored by the
compiler. Some examples of comments can be:
// I declare my variables
int width, height;
int task; // This variable saves the calculated area.
// The following statement is never executed
// Console.WriteLine ("Hello");
If we need to put a lot of information in our comments, it may be useful to explain it in several
lines, i.e., make a block of comments. To do this, we open our comment block with a slash
followed by an asterisk, /*, and end it with an asterisk first, followed by a slash */. Everything in
between these delimiters will be taken as a comment, and the compiler will ignore it.
Let's look at an example of a multi-line comment:
/ * The next section calculates the area and uses the variables
height - to save the height of the rectangle
width - to save the base of the rectangle
*/
Thus we see how the comments placed in several lines are taken as a single comment. This is
very useful for future reminders.
Comments only serve us as human beings to help us understand the program code. The compiler
ignores all comments and does not take them into account at the time of compilation. Comments
do not make the program slower or faster. However, they are very useful when we see the code.

Show Variable Values in the Console


Since we can save values, we would also like to be able to display them when necessary.
Fortunately, using the WriteLine() method or the Write() method, we can do it. In this case, we
will not use the string as before, what we will use is a format string and a list of variables. The
format string allows us to place the message to be displayed and indicate which variable we will
use to display its content and also where in the string we want it to be displayed. In the list of
variables, we simply place the variables that we want to show.
The format string is treated as a normal string, but we add {} where we want the value of a
variable to be placed. Inside {}, we must place the index of the variable in our list. The indexes
start at zero. If we want the value of the first variable to be shown in the list we place {0}, and if
it is the second one, then we place {1} and so on. The list of variables is simply placed after the
string, separating the different variables with commas.
For example, we can show the value of a variable as follows:
Console.WriteLine ("We have {0} in the variable", cost);
Since we only have one variable in our variable list, then we put {0}. But we can also show the
value of two variables or more, as the following example shows:
Console.WriteLine ("The first is {0} and the second is {1}", cost, value);
Now let's look at an example with what we have learned.
using System;
using System.Text;
namespace BaseApplication
{
class Program
{
private static object value;
private static int price;
static void Main(string[] args )
{
// We declare variables
int cost;
// We initialize the variables
cost = 50;
value = 75;
price = 125;
// We show a value
Console.WriteLine("The value inside of cost is {0}", cost);
// several variables
System.Console.WriteLine("Value is {0} and price is {0}", value, price);
// twice the same variable
Console.WriteLine("Value is {0} and price is {0} with value of {0}", value,
price);
}
}
}
Once we have compiled the application, we will obtain the result shown in the figure below.

Arithmetic Operations
Being able to save information is very important, but it is much more important that we can
retrieve and manipulate that information to do something useful with it. For this, we must begin
to perform the basic arithmetic operations: addition, subtraction, multiplication, and division,
something very common in any computer system.
When we want or need to perform an arithmetic operation, we must use an operator. Each
operation has its own operator, which is in charge of processing the numbers, performing the
determined calculation, and then returning the desired result.
Operator Description
= Assignment. This operator is already known to us.
+ Sum. We can add the values of the variables or numbers
- Subtraction. To subtract the values of the variables or numbers.
* Multiplication. Multiplies the values of the variables or numbers.
/ Division. Divide the values of the variables or numbers.
% Module. It gives the remainder of the division.

Let's see some examples of how to use these operators. Let's imagine that we have already
declared and initialized the variables. To save the sum of two numbers in the result variable, we
do the following:
result = 5 + 3;
As we have seen, the expression on the right is assigned to the variable, so in this case, the
expression 5 + 3 is evaluated, and its result, which is 8, is stored in the result variable. At the end
of this sentence, the result variable has a value of 8, which can be used within the same function
or in the procedure where it was declared.
Operations can also be performed with variables and numbers. Suppose that variable a has been
declared and assigned a value of 7.
result = a - 3;
Again the expression a-3 is evaluated since the value inside of a is 7. The evaluation gives the
value of 4, which is assigned to the result variable.
If we want, we can only work with variables. Now we will assume that variable b has been
declared and that we have assigned the value 8.
result = a * b;
Then, the expression a * b is evaluated, which gives the value 56, which is assigned to the
variable result at the end of the expression.
If what we want is division, we can do it as follows:
result = a / b;
In this case, divide the value of a by the value of b. The result is 0.875. Since the number has
decimal values, we must use variables of some type that allow us to save them as float or double.
And finally, we have the module.
result = a% b;
In this case, we receive as a result the value of the remainder of dividing a by b.
Let's see a small program where what is learned in this section is shown.
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// We declare the variables, now of floating type
float a, b, result;
// We initialize the variables
a = 7;
b = 8;
result = 0 ;
// sums
Console.WriteLine("Sums");
result = 3 + 5;
Console.WriteLine("Result = {0}", result);
result = a + 3;
Console.WriteLine("Result = {0}", result);
result = a + b;
Console.WriteLine("Result = {0}", result);
// Subtract
Console.WriteLine("Subtract");
result = a - b;
Console.WriteLine("Result = {0}", result);
result = b - 5;
Console.WriteLine("Result = {0}", result);
result = b - a; // Variable b is subtracted from
Console.WriteLine("Result = {0}", result);
// Multiplications
Console.WriteLine("Multiplications");
result = a * 5;
Console.WriteLine("Result = {0}", result);
result = a * 3.5f;
Console.WriteLine("Result = {0}", result);
result = a * b;
Console.WriteLine("Result = {0}", result);
// Divisions
Console.WriteLine("Divisions");
result = a / 3;
Console.WriteLine("Result = {0}", result);
result = a / b;
Console.WriteLine("Result = {0}", result);
result = b / 2.5f;
Console.WriteLine("Result = {0}", result);
// module
Console.WriteLine("Module") ;
result = a % b;
Console.WriteLine("Result = {0}", result);
}
}
}
We can see the execution in the following figure:

The most common errors in mathematical expressions are forgetting the semicolon, making the
wrong assignment, misspelling the variable name, and incorrectly grouping operations. Using
parentheses for grouping helps a lot to reduce errors.

Precedence of Operators
So far, we have used simple arithmetic expressions, but in real life, more complicated
expressions may be needed. So, if these expressions are not placed properly, this can lead to
problems.
For example, let us look at the following expression.
result = 3 * 5 + 2;
This expression presents a problem for us at this time. We don't know if you first do 3*5 and add
2, which results in 17, or if you add 5+2 and then multiply it by 3, which results in 21.
The way to find out is through operator precedence. This tells us the order in which the
operations are carried out. This order depends on the type of operator used. Some operators have
more precedence than others, i.e., they are executed first.
The following table shows the precedence of the operators we have seen so far in C#. They are
listed from highest to lowest precedence.

Operator Description

* Multiplication

/ Division

% Module

+ Addition

- Subtraction

This means that when we have an arithmetic expression like the one in the example, first, the
multiplication would be carried out and then the addition, so with this, we can deduce how C#
would evaluate the expression.
But sometimes it would be better if we could organize our expression to make it easier to read
for us or to indicate precisely how to do the operation. For us to organize an expression, we make
use of parentheses. Each section we have in the parentheses is evaluated as an expression, and
the result is passed to the rest of the expression. Suppose we have the following expression:
result = (3*5) + 2;
We see that using the parentheses a part of the expression has been grouped, so it is evaluated
and equivalent to:
result = 15 + 2;
This, in the end, evaluates in:
result = 17;
Let's see another example of how we can use the parentheses to indicate how we should evaluate
the expression.
result = 3 * (5+2);
The first thing that happens is that the expression in the parenthesis is evaluated.
result = 3 * 7;
That gives us the value:
result = 21;
Let's look at a slightly more complicated example.
result = (3+7) * (36 + 4 *(2+5));
Let's see what happens:
result = 10 * (36 + 4 * 7);
Then we continue to evaluate:
result = 10 * (36 + 28);
This gives as a result:
result = 10 * 64;
And in the end, we get:
result = 640;
Fortunately, C# does all these evaluations and all these calculations for us, but now we know
how it happens, and we know that we can use the parenthesis to organize our arithmetic
expressions.

How to Ask the User for Information


We have used variables to store values, and with the arithmetic operators, we have been able to
perform mathematical calculations. However, all the values we have used are placed directly in
the program code. This is not very comfortable since if we want to do a calculation with different
values, it is necessary to modify the code and recompile it. It would be more useful if we could
get the user to put in the values he needs when the program runs. For this, C # provides us with a
method that belongs to the Console class. The method is called ReadLine(). This does not need
any parameter, so its parentheses will remain empty, and it returns a string that contains what the
user typed with the keyboard.
This is a simple way to request information from the user. Suppose we want to ask the user for
their name, which we will use later to greet them. For that, we put the following code:
input string = "";
Console.WriteLine ("Enter your name");
input = Console.ReadLine ();
Console.WriteLine ("Hello {0}, how are you?", Entry);
In this program snippet, it is important to note how the value obtained by ReadLine() is assigned
to the input string type variable. If we do not put a variable that receives the value of what is
written by the user, it will be lost. When we use ReadLine (), we must do it as shown. Once we
receive the user input, we can work with it without problems.
A common mistake with large expressions is to forget to close a parenthesis properly. In Visual
Studio, it is easy to see which parentheses are pair because when you select one of them, its
partner will be highlighted. For each opening parenthesis, there must necessarily be a closing
parenthesis. When this is not done correctly, it is called a parenthesis imbalance.

Conversion of Variables
The ReadLine() method presents us with a limitation at this time since it only returns the value as
a string. But we cannot use a string in arithmetic operations or assign it directly to a numerical
variable.
What we have to do is convert that numerical data stored as a string to a numerical value useful
for our purposes. C# provides us with a class that allows us to make conversions between
different types of variables. This class is known as convert and has a large number of methods
for conversion. Here we will only look at how to convert to integers and floats, as these are the
types we will be working with through this book primarily. However, the other methods are used
similarly, and we can find the necessary information about them in MSDN (Microsoft Developer
Network).
If we want to convert from the string type to the int type, we will use the ToInt32() method. This
needs a parameter, which is the string we want to convert. The method returns an int type value,
so it is necessary to have a variable that receives it.
An example of this is:
a = Convert.ToInt32(input);
Similarly, we can convert the string to a float type variable. In this case, we will use the
ToSingle() method. This also needs a parameter, which is the string that contains the value to
convert. Since a float value returns, then we must have a float type variable that receives it.
value = Convert.ToSingle(input);
Since we have the values converted to numbers, then we can make use of them. Let's see an
example where we ask the user for information.
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// We declare variables
string input = "";
int a = 0, b = 0, result = 0;
// We read a string
Console.WriteLine("Enter your name");
input = Console.ReadLine();
int Entry = 0;
Console.WriteLine("Hello {0}, how are you?", Entry);
// We read two values and add them together.
Console.Write("Give me an integer:");
input = Console.ReadLine();
// Convert the string to integer
a = Convert.ToInt32(input);
Console.Write("Give me another integer:");
input = Console.ReadLine();
// Convert the string to integer
b = Convert.ToInt32(input);
// Add the values
result = a + b;
// We show the result
Console.WriteLine("The result is {0}", result);
}
}
}
Now let's compile and run the application. To enter the data, simply type it with the keyboard
and when finished press the ENTER or RETURN key.
It is also possible to convert from numbers to strings. For this the ToString () method is used,
which is available in all numeric C # types. In this way we can use the information of the
numerical variables in functions or methods that work with strings. The method does not change
the type, it just returns a string containing the text of that value.

How to Solve Computer Problems


Since We Know Some Elements Of The language, it is now important to learn how to solve
problems on the computer. There are different methodologies for doing it, but since this is a book
for people with no programming experience, we will learn a simple method. As we have already
mentioned, C # is an object-oriented language. However, first, we will learn a structured
methodology, which will allow us to have experience in solving problems. Then we will be able
to learn the object-oriented methodology more easily.
The methodology we learn is based on the concept of subdivision of problems. That is, we take
the general problem and then break it down into smaller problems, and if necessary, break these
subproblems into smaller problems, until we can solve the subproblem directly.
To solve any problem, the first thing we have to do is understand it. You have to understand
precisely what is required. The problems will have information. In many cases, the problem
directly gives us information. This type of information is known as explicit information. But
sometimes it also happens that the problem does not give us the information directly, so it is
important to understand it well. In this case, we must infer the information from other data that it
provides us or look for it somewhere else. This type of information is known as implicit
information. Fortunately, implicit information, in many cases, is easy to find or is part of the
general knowledge of any person.
Since we have the subdivided problem and the recognized data, we proceed to reperform the
algorithm. Let's remember that the algorithm is the series of steps necessary to solve the
problem. Also, it can be defined by using a flow chart or written in something that we will call
pseudocode. The programmer can create the algorithm with his preferred method.
When the algorithm is finished, we proceed to test it. At this stage, we can test on paper if
everything works well. If there were any wrong results, then the algorithm can be corrected, and
the process repeats until we have an algorithm that works properly.
The last step is to pass the algorithm to a computer program. If all has been done correctly, the
program should be executed at the first attempt. Many people are surprised that to make a
computer program, the last step is to put it into the computer, but this is the right way. Some non-
professional programmers try to make the program directly on the computer, but this leads to
many logic and data errors, and the time it takes to solve the same problem is longer. It is
difficult to get it to run correctly on the first attempt.
Although the methodology we have just presented is long, it can actually save up to 50% of the
resolution time compared to someone who programs directly on the computer. Now that we have
started, it is good to get into good programming habits right from the start. In the future,
especially when the problems you solve are complicated, you will see the benefits.
Sometimes we will need variables that support us to solve some calculation or process. We will
call these job data. Job data is discovered when we do problem analysis. If we omit any during
the analysis, it is always possible to add it during the development, but this must be the exception
to the rule.

Elements of a Flowchart
It is time to learn the basic components of a flowchart. With these diagrams, we can represent the
algorithm, and they are easy to make and understand. Another advantage they have is that they
are language independent, which gives us the flexibility to solve the problem and use our
solution in any language.
The flowchart is a graphical representation of the algorithm and has different components. Each
component is a figure, and it represents a type of activity. Inside the figure, we place a
description of the step that is happening there, using arrows we indicate which is the next step,
and it gives us the idea of the general flow of the algorithm. Sometimes, we add extra
information to the arrows, but we will see this later. Although at this moment we will not use all
the components of the flowchart, we will know the most important ones, since in the following
chapters we will use them.
The first component is oval-shaped and is known as the terminator. This is used to indicate the
beginning or the end of the algorithm. When we see it, we can immediately know where the
algorithm starts, and we can continue from there. Remember that algorithms must have an end to
be valid. If the terminator is started, we put the message inside Start, and if the terminator
indicates where the algorithm ends, then the message: End.

The next element is known as a process. This has the shape of a rectangle and serves to indicate
that a process must take place there precisely. The description of the process is indicated inside.

Similar to the process, we have a pre-defined process. Its shape is also a rectangle, but it has two
lines on the sides. It is used to indicate that we will make use of a process that has already been
defined elsewhere.
An example of this would be a method, like the ones we have already used. We'll mainly use it to
indicate calls to functions or methods defined by ourselves.
Our next element is known as a condition. We will use this element when we learn how to make
the program to make its own decisions. Basically, it serves to make a selection among the
possible paths of execution of the algorithm, which will depend on the value of the evaluated
expression. Its shape is like a rhombus, and from the corners of this one, the arrows will appear
towards the possible paths of execution of the algorithm.

Then we find a component known as data. Its shape is that of a parallelogram, and we can use it
to indicate the output or input of the data.
An example of this would be when we carry out a request for a value to the user or when we
display a value on the screen. Inside it, we indicate what data is requested or presented.
We have seen the main elements of the flow chart. Now we can do an exercise that shows the
solution of a problem on the computer.

Solving Computer Problems


Let's start with a simple and easy to understand the problem. For this problem, we will follow all
the steps that we have mentioned until we reach the final computer program. First, we have a
description of the problem.
Make a computer program that calculates the area and perimeter of a rectangle given its sides.
Once we have the problem and understand it, then we proceed to subdivide it into smaller
problems that are easy to solve. This subdivision can be made by utilizing a diagram. For this, it
must be remembered that if any of the problems are still difficult, we can continue subdividing it.
As an example, we will exaggerate the subdivision a bit in this case. The problem would be
subdivided, as shown in the following figure.

Since we know the problem and have subdivided it into several sub-problems, we can more
clearly identify the data we need to work on it. The description of the problem provides us with
two explicit pieces of information: the area and the perimeter. But we also immediately
recognize two implicit data that are necessary: the height and the width of the rectangle.
We know that we need a string to receive the value written by the user, but as such, this string is
not part of the problem. However, it helps us to solve it so that the string will be working data.
The data we have identified will be placed in a table as follows:

Name Type Initial Value


area float 0.0
perimeter float 0.0
width float 1.0
high Fleet 1.0
value String ""

We have decided to use the float type since we can have decimal values in the perimeter
calculation. Since a rectangle with a width or height of 0 does not make sense, we have selected
1 as the initial value for these variables.
Now the most important step comes: creating the algorithm. However, if we observe the way we
subdivide the problem, we can see that it gives us an indication of the steps that need to be put in
the algorithm.

With this information, we created the algorithm with the flowchart. In it, the sequence of steps
appears in the correct order. Let's see how the diagram looks.
We can observe how we have used the trapezoid when it is necessary to ask or show data to the
user. The calculations with the corresponding formula are in the rectangles since they are various
processes, and the terminators represent the beginning and end of the algorithm.

The Code of Our Application


We already have everything we need to create the program code. For this, we will use the base
application we already have. As we have created a data table, we already know all the variables
needed for the application. So we will take this table and put the data as variables.
// We declare the variables that we need
float area = 0.0f;
perimeter float = 0.0f;
width float = 1.0f;
height float = 1.0f;
string value = "";
With the variables defined, we then proceed to code each of the steps of the algorithm. We go
step by step and in the same order in which they are found, and we see that the first thing is to
ask for the width of the rectangle.
Console.Write ("Give me the width of the rectangle:");
value = Console.ReadLine ();
width = Convert.ToSingle (value); // Convert to floating
The next thing the algorithm does is ask for the height of the rectangle, so the necessary code is
as follows.
Console.Write("Give me the height of the rectangle:");
value = Console.ReadLine ();
height = Convert.ToSingle(value); // Convert to floating
Once we have obtained all the input data, we can say that we already have a process. This
process will be in charge of calculating the area that the rectangle occupies. Let's see the example
below:
area = width * height;
In the next process we have, the perimeter is calculated.
perimeter = (width + height) * 2;
If we look closely at the algorithm and also at its next step, we will find that we are working with
data again. But in the latter case, we only display the calculated area value on the screen. Let's
see to understand better what we are talking about.
Console.WriteLine ("The area is: {0} square units", area);
As the last step of the algorithm that is being executed, it only remains for us to display the
calculated value of the perimeter in our console application.
Next, we write the last necessary code in our application:
Console.WriteLine ("The perimeter is: {0} units", perimeter);
So far, we have seen a complete and complex way of handling, from a console application, the
manipulation of data, variables, and mathematical operations, with a clear example studied step
by step. With this, we have already finalized the application code. Now we can compile and test
it, and everything should work properly if we haven't forgotten to put anything in it.
Learning to program requires a lot of practice and a lot of experimentation. It is good to try the
programs and see what happens. We should not be afraid of making mistakes when we are
learning. It is also good to check the documentation for functions, classes, and methods as it is
possible to find utilities in these for the future.
To program computer software, we need to know a programming language. One of these
languages is C #. The programs must be ordered and indicate step by step what to do, and for
this, we make use of algorithms. The information is stored in variables, and the type indicates the
information it may have inside, making it possible to display data in the console and also request
it from the user. Arithmetic operators allow us to carry out mathematical operations, provided we
use a correct problem-solving methodology.
Chapter 3
The Program Makes Decisions

In the programs created so far, we have seen that the algorithms had only one sense of resolution.
In this chapter, we will learn other ways to have our programs make decisions based on the
analysis of different parameters. We will also learn how to create algorithms with varying paths
of execution to be able to solve problems based on previous analysis.

Decision Making
Not all problems are solved linearly, sometimes it is necessary to have to make a decision or
execute certain actions when a condition is met, and others when it does not. Let us suppose that
our problem is to maintain the temperature of a bucket of warm water. To do this, we can add hot
or cold water. In this problem, we would need to decide what kind of water to add.
Similarly, there are many problems that we need to know a condition or make a decision on how
to solve them. In C#, it is easy to achieve this since the language provides us with different tools
to cope with it. We will have to use expressions, and these will be evaluated. In this case, we will
use relational expressions and logical expressions, which will be evaluated, and depending on the
result of that evaluation, certain steps of the algorithm or others will be carried out. Let's start by
knowing the expressions we need.

Relational Expressions
Relational expressions are used to express the relationship between two values. Values can be
contained within variables or explicitly placed. These expressions, like arithmetic expressions,
have their own operators. The expression will be evaluated, but the result of the evaluation will
have only two possible values: true or false.
Both types of values bool and true are used to indicate that the evaluated expression is true. The
value of false for its part is used to indicate that the evaluated expression is false.
Let's start by getting to know the relational operators first. Then we will look at examples of
relational expressions with their resolution.

Relational Operators
In the table below, we can see the relational operators in C#. The way their signs are written is
the way we must place them in our program.

Sign Operator
== Equality
!= Not the same
> Greater than
< Smaller than
>= Higher than the same
<= Less than equal
The equality operator is represented by two equal signs together without space. Placing a single
equal sign indicates that the operator will be for assignment. This can lead to logic errors because
an assignment always evaluates to true, but equality does not. This operator is the simplest.
Suppose we already have the variables and initialize them with the following values:
int a = 5;
int b = 7;
int c = 5;
int d = 4;
Now we will create our first expression and evaluate it:
a == c
As the value contained in a is 5, and the value contained in c is also 5, we see that 5 is equal to 5,
so the expression is evaluated as true. Let's see what happens in the next expression:
a == d
In this case, the value contained in d is 4, so the expression 5 equal to 4 is not fulfilled, and the
value of the expression is false. On the right side and the left side of the expression, we can place
any value, variable, or expression. If we were to place an expression, first, it would be evaluated.
Then we would proceed to evaluate the main relational expression.
a == (3 + 2)
In this case, 3 + 2 is evaluated as 5, and then 5 equals 5, which gives us the final value of the true
expression. Another example is the following:
(b - 2) == d
When evaluating b - 2, we get 5, and then the expression is 5 equal to 4, which obviously gives
us a false final result.
This is how relational expressions are evaluated, and now we'll see more examples with other
operators. We also have the inequality operator, which is created employing an exclamation
mark and then the equal sign.
a != 7
In this case, we have 5 that is not equal to 7, which is true, and we get the true value as a result of
the evaluation.
a != c
For this expression, we have 5 that is not equal to 5, and the expression is evaluated as false,
which gives us false as a final value. The > operator is used to evaluate a relationship of the type
greater than. If the value on the left side is greater than the value on the right side, it will return
true; otherwise, it will return false.
b>a
This is 7 greater than 5 and results in true.
a>b
In this case, 5 greater than 7 is false, and the result of the expression is false.
b>b
This expression gives us 6 greater than 6, which, if we analyze all the steps up to here, indicates
that it is false as well, and we get false as a result.
In the < operator, we evaluate a relationship of the type less than. It gives true as a result when
the value on the left side is less than the value found on the right side. If this is not true, then the
value returned will be false.
d<a
We have 4 less than 5, which is true, and the result is true.
d < (a - 3)
The expression to be evaluated is 4 less than 2, and it is had false as a result of the expression.
d<d
This expression also results in falsification, since 4 less than 4 is not true. To evaluate whether a
value is greater than or equal to another value, we use the >= operator. The way it works is
similar to the other operators.
b >= a
For this expression, we have 7 greater than equal to 5, it is true, and it gives true value.
b >= (a + c)
In this case, we would get 7 greater than equal to 10, which we know is false and, therefore, as a
result, and we would get false.
b >= b
Here we compare the difference in result in relation to using >= instead of >. For this expression,
we evaluate 7 greater than equal to 7. This is true, and the final result is true. Similarly, we have
the <= operator, but it evaluates in reverse.
a <= b
The expression to be evaluated is 5 less than equal to 7, and we get true as a result.
(a + c) <= b
In this case, we have 10 less than equal to 7, and it is false.
(a + 2)<= b
In this last expression, 7 less than equal to 7 is true, and again, we get true as a result.
A very common mistake that happens when you start programming in C # is to confuse the
equality operator with the assignment operator. If you get an error in an expression, you need to
check this. Let's not forget that the assignment has an equal sign, and equality equals a double
sign.
Operators that are written with two signs must be written correctly. It is not the same> = that =>.
This can lead to syntax errors, but precisely writing them will make them correct. We must also
remember that they are written without spaces between the signs since this leads us to another
syntax error.

Using if
We have already learned how to use relational expressions and the return type. It is time to do
something practical with them. This type of expression is used in different cases but generally in
selective or repetitive structures.
The selective structures will be studied in this chapter, the repetitive ones in a later chapter.
Selective structures are those that allow us to make a selection between two or more possible
execution routes. The selection will be made based on the value of an expression. This
expression can be a relational expression. Our first selective structure is known as if, which is
conditional If. If such a thing happens, then do such a thing. The use of the If is simple:
if (expression)
Statement to execute
The use of If requires that we have to put an expression for evaluation in the parentheses. If the
result of this expression is true, then the statement to execute is carried out.
If the evaluation result is false, then the statement to be executed is never carried out, or in other
words, it is ignored.
In the flowchart, the If is represented by a rhombus. Inside the rhombus, we place the expression
to evaluate, from the corners, we get an execution path if the condition is met or in the case that
it is not met.
Let's see the first example where we can use if and the expressions. We will create a program
that asks the user for a number, and the computer must say if the number is positive or negative.
To see the algorithm of this program, we create its flow chart and include the necessary if's.

using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
public static string Value { get; private set; }
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
int number = 0; // Where we keep the number
string value = ""; // To save the string given by the user
// We ask for the number
Console.Write("Give me an integer:");
Value = Console.ReadLine();
number = Convert.ToInt32(value); // Convert the string to integer
// We use if with the expression for the
case of positives
if (number >= 0)
Console.WriteLine("The number {0} is positive", number); // is
executed if number> = 0 is met
// We use if
with the expression for the case of negatives
if (number < 0)
Console.WriteLine("The number {0} is negative", number); // run if
number <0 is met
}
}
}
The first part of the program is very easy to understand. After this one, we came across the first
if-sentence. For this, if you have the expression number >= 0. If that expression is evaluated as
true, then the next statement is executed; otherwise, it will be ignored, and the program will
continue.
Suppose that the value stored in number is 3, and then the relational expression returns a value of
true. When true is obtained, the If leads to execution and the message that a positive number is
executed.
Then we continue with the next If. For this one, the expression is number < 0, as in this example
number is worth 3, then the expression is evaluated as false, so, while the value of the expression
is false, If will not execute at any time the message that says that the number is negative. This is
exactly what we want this program to do from the beginning.
This is the result of the execution when we pass a positive number for the program.

In this case, we give a negative number, and we can observe the behavior of the program.
When we use if, we should never put a semicolon after the parentheses since doing so is not a
syntax error but a logic error. The compiler interprets this as if we want an empty statement to be
executed when If is true. We see that the If statement always holds regardless of how the
expression is evaluated, we may have this error.
This is a good time to start experimenting in our developments, changing the values, both
negative and positive, including zero and see how our program will respond.
As we saw, the If can be very useful for the program to make the correct decision; however, it
has only been able to execute a statement. We will often encounter the case when we need more
than one statement to be executed if the condition is met. A good option to solve this problem
found is to put a code block to If. In this case, the code block will be executed whenever the
expression inside If is evaluated to true, and the entire code block will be ignored whenever the
expression is evaluated as false.
When we use if, we should never place a semicolon after the parenthesis since doing so is not a
syntax error but a logic error. The compiler interprets this as if we want an empty statement to be
executed when if is met. If we see that the if statement is always fulfilled no matter how the
expression is evaluated, we may have this error.

Code Block With If


The code block is a set of grouped statements and must be opened with {and closed with}, and it
will be composed as follows:
if (expression)
{
Judgment 1;
Judgment 2;

Judgment n;
}
Let's see an example where we make use of this. We know that the division between zero is not
defined, so we must make a program that asks the user for the dividend and the divisor, but when
the divisor is zero, it does not carry out the division. As always, we first do our analysis and
create the algorithm in the form of a flowchart.
This is the flow chart of the algorithm. We may think that what we have grouped is what is
inside the If code block.
The program is as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// Required variables
float dividend = 0.0f;
float divisor = 1.0f;
float result = 0.0f;
string value = "";
// We ask for the dividen d
Console.WriteLine("Give me the dividend:");
value = Console.ReadLine();
dividend = Convert.ToInt32(value);
// We ask for the divisor
Console.WriteLine("Give me the divisor:");
value = Console.ReadLine();
divisor = Convert.ToInt32(value);
// If the divisor is valid, then we do the division if (divisor! = 0.0f)
{
// We do the operation
result = dividend / divisor;
// We show the result
Console.WriteLine("The result of the division is {0}",
result);
}
}
}
}
We can see that we have placed a code block for if. If the divisor expression != 0.0f is true, then
the code block where we have the operation and the result display is executed. If the expression
is evaluated as false, the whole code block is ignored and the statements inside it are not
executed.
Now we can compile the program and give values to test and observe the behavior. We see that
indeed when the divisor has a value of zero, the operation and the message are not executed.

In this case, seen here, the division is executed, and then the result is shown.
As we have placed the value zero in the divider, the division is not carried out.
It is always convenient to check the program execution and put values that can cause problems to
detect any logic error. We can test positive, negative, zero, fractional, and so on. If we encounter
problems with the values, we can use the if to validate the values before using them.

The Use of Else


With the previous programs we were working with, where we used the if statement, we have
seen that we can indicate that a certain statement is executed when we want a condition to be
met. However, you may find that sometimes we need a statement to be executed when the
condition is met and another statement to be executed when the condition is not met. If this is the
case, one way to solve it would be to place an If with a condition and then another If with the
condition that complements the first one. We have done this before in the program of positive
and negative numbers. However, there is a simpler way than the one used in this program to do
it. This way can be very useful to simplify the logic and not to have to place so many ifs inside a
sentence. To achieve this, we will use else.
We always use else after an If statement, as else can't be used alone. We have to place our code
in the following way:
if (condition)
Judgment1;
else
Judgment2;
If the condition is evaluated as true, then statement 1 is executed. But when the condition is
evaluated as false, statement 2 is executed. To do this, we chose to represent this example, the
program of the positive and negative numbers.
The first thing we have to analyze is the graph of the flow chart. As we use an if-else type
structure or statement, one of the rhombus outputs corresponds to the code that is executed when
the expression is evaluated as true (If). The other output is the one we use for the statement that
is quoting the axis when the expression is evaluated as false (else).

Here we can clearly see the If path and the Else path.
The code of our program would be composed as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
int number = 0; // Where we keep the number
string value = ""; // To save the string given by the use r
// We ask for the number
Console.Write("Give me an integer:");
value = Console.ReadLine();
number = Convert.ToInt32(value); // We convert the string to whole
// We use if with the expression for the case of positive if (number > = 0)
Console.WriteLine("The number {0} is positive", number); // I know
executes if number > = 0 is met else
Console.WriteLine("The number {0} is negative", number); // I
know executes if number > = 0 is NOT met
}
}
}
We can see that the program is simpler, and the logic has been simplified, which makes it easier
to read and maintain the program. But it does not mean that we should always use If-Else. We
have to use it when we have something that we want to execute fulfilling previously the specified
condition, and something that we want to execute when this one is not fulfilled. Abusing if-else
or using it senselessly will complicate the logic of the program, but using it well helps us.
It is always advisable to check the execution of the program and place values that may cause
problems to detect any logic errors. We can test positive, negative, zero, fractional values, etc. If
we find problems with the values, we can use the if to validate the values before using them.

Using Else With Code Block


With the If we can put a code block in else, this would allow more than one statement to be
executed when the If-condition is not met. We should not forget to place the code block starting
with a brace, {, and ending it with the closing brace}. Inside the code block, we can place any
valid C # statement.
For example, we can modify the division program to make use of the else statement. In this case,
what we will do is that, when the divisor is equal to zero, we will send the console an error
message, and when it is not, we will carry out the division. Let's first see what the flowchart
looks like with these changes. It's easy to notice the else's path.
The program code is modified as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application her e
static void Main(string[] args)
{
// Required variables
float dividend = 0.0f;
float divisor = 1.0f;
float result = 0.0f;
string value = "";
// We ask for the dividend
Console.WriteLine("Give me the dividend:");
value = Console.ReadLine();
dividend = Convert.ToInt32(value);
// We ask for the divisor
Console.WriteLine("Give me the divisor:");
value = Console.ReadLine();
divisor = Convert.ToInt32(value);
if (divisor == 0)
Console.WriteLine("The divider is invalid");
else
{
// We do the operation
result = dividend / divisor;
// We show the result
Console.WriteLine("The result of the division is {0}",
result);
}
}
}
}
In this way, we can handle two options, one for the divisor with the value of zero and another for
when the divisor is valid.

How to Use Nested If


The statement or block of code that executes if can be any valid statement or block of code valid
in C #, this includes another if. This means that we can put if inside the code to execute from a
previous if. When we do this, we must be careful to avoid logic errors. This is known as nested
if. Let's look at an example of this. We have to make a program that will ask for the type of
arithmetic operation that we want to execute and then the two numbers with which to carry out
the operation.
The result will be displayed on the screen. The program will have the following code:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Here starts the application
static void Main(string[] args)
{
// Required variables
float a = 0.0f;
float b = 0.0f;
float result = 0.0f;
string value = "";
int option = 0;
// We show the menu
Console.WriteLine("1 - Sum");
Console.WriteLine("2 - Subtraction");
Console.WriteLine("3 - Division");
Console.WriteLine("4 - Multiplication");
Console.Write("What operation do you want to do:");
value = Console.ReadLine();
option = Convert.ToInt32(value) ;
// We ask for the first number
Console.Write("Give me the first number:");
value = Console.ReadLine();
a = Convert.ToSingle(value);
// We ask for the second number
Console.Write("Give me the second number:");
value = Console.ReadLine();
b = Convert.ToSingle(value);
// We check for sum
if (option == 1)
result = a + b;
// We check for subtraction
if (option == 2)
result = a - b;
// We check for division
if (option == 3)
if (b!= 0) // this if is nested
result = a / b;
else // This else belongs to the second if
Console.WriteLine("Invalid splitter");
// We check for multiplication
if (option == 4)
result = a * b;
// We show the result
Console.WriteLine("The result is: {0}", result);
}
}
}
The program is simple, we only need if for each operation, but in the case of division, we will
need to place another if to verify that the divisor is not zero. That is, for the division, we will
have nested ifs. The flow diagram of the application is shown in the following figure.
In the previous program, we saw how the If was used for the division, and we just have to be
careful with else to know what if belongs to. When in our programs, we make use of indentation,
that is, placing spaces before the statement, we can make it easier to recognize which part of the
code belongs to which section. Some code editors do this for us automatically, and visually it is
easier to recognize the code.
When we put an if inside the code that can execute a previous If, we are saying that we have a
nested If. This type of structure is very useful and can help us optimize programs, but we must be
careful to use it correctly to avoid logic errors. When coding, it must be done in an orderly
manner.

If-Else Ladder
Another structure that can be used is the if-else ladder. One of its main functions is to optimize
the execution of the code. Sometimes they are necessary because the logic of the program
requires it. As with nested if, they should not be used without planning since not programming
them correctly can lead to logic errors that can be difficult to solve.
Now let's learn how we can use them to make our code more efficient. If we look at the program
of mathematical operations, we have an if for each operation. This means that when our program
runs, regardless of whether addition or multiplication has been selected, at least four if must
always be run—the If can be expensive operations since expressions have to be evaluated.
The way to optimize this is with an if-else string. The concept is simple and consists of putting
an If in the else statement.

This would look like the following code:


if(expression 1)
Sentence 1
else if(expression 2)
Sentence 2
else if(expression 3)
Sentence 3
As we can see, a figure is generated that looks like a ladder and, therefore, its name. Let's modify
the program of the mathematical operations. First of all, its flow chart is as shown in the figure
below.
In this flow chart, we can see our if-else ladder.
Let's modify the program code, placing it as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// Required variables
float a = 0.0f;
float b = 0.0f;
float result = 0.0f;
string value = "";
int option = 0;
// We show the menu
Console.WriteLine("1 - Sum");
Console.WriteLine("2 - Subtraction");
Console.WriteLine("3 - Division");
Console.WriteLine("4 - Multiplication");
Console.Write("What operation do you want to do:");
value = Console.ReadLine();
option = Convert.ToInt32(value);
// We ask for the first number
Console.Write("Give me the first number:");
value = Console.ReadLine();
a = Convert.ToSingle(value);
// We ask for the second number
Console.Write("Give me the second number:");
value = Console.ReadLine();
b = Convert.ToSingle(value) ;
// We check for sum
if (option == 1)
result = a + b;
// We check for subtraction
else if (option == 2)
result = a - b;
// We check for division
else if (option == 3)
if (b != 0) // this if is nested result = a / b; else // This else belongs to the
second if
Console.WriteLine("Divisor not valid");
// We check for multiplication else if (option == 4) result = a * b;
// We show the result
Console.WriteLine("The result is: {0}", result);
}
}
}
If we run the program, we will see that it does exactly the same as the previous version. But
where is the optimization? If we look at the code, we can find it. Suppose the user has selected
option 1, that is, the sum.
This satisfies the condition of the first if and executes the addition operation. But we know that
both the if or else are not executed together. If we look, we see that all other operations are in the
else path, so they are ignored.
Before we had to do four ifs all the time, now only one was done, and the others were avoided.
That's where the optimization is. In other words, in the previous program, there were always four
ifs, and in the new one, in the best case, we have only one if, but in the worst case, we have four.
That's how the optimization was carried out.
When we use if-else, either or both can have a statement or a block of code. Both do not need to
be the same. The selection between the statement or the code block gives us the algorithm and
the logic needs that we have. Some programmers place the code block out of habit, even if it
only has one statement.
Sometimes it happens that when we have nested, one or more of the If's can have else. Then we
don't know whom it belongs to, and the Else will always belong to the closest if that no longer
has an else assigned. The best way to avoid problems with this is to use code blocks, even if we
only have one statement in the block.
If the if-else ladder seems difficult to read, we can use code blocks to group the sections. This
will make it easier to understand and read the logic of the application. The application can be
solved with normal If's.

Logical Expressions
Like arithmetic and relational expressions, logical expressions have their own operators. These
are: and, or and not.

Operator Meaning
&& And
|| or
! Not
Here we have the logical operators used in C #.

The Use of the Conjunction


Let's get to know them. The first operator is y, known as a conjunction. To use this operator, you
need to have two expressions—one expression on the left and the other on the right. Expressions
are evaluated by returning true or false values. With the conjunction, the expression is evaluated
as true only when both expressions are true. The following is the truth table for this operator:

P Q P && Q
true true true
false true false
true false false
false false true

Suppose we have to decide whether we should fill the vehicle's gas tank. We do this if the tank is
less than 50% full and if the distance to be driven is more than 200 km. As we can see, we have
to use the conjunction since we have two conditions, and both of them must be met for the filling
of the gasoline to take place. If we place this as an expression, it would be:
if(tank < 50 && distance > 200)
Refueling
Suppose that tank is 25 and distance is 350 when evaluating 25 < 50 and 350 > 200; we have the
following.
if(true && true)
Refueling
In our table, we know that when both expressions are true, then the conjunction is fulfilled, and
the logical expression evaluates us to true.
if(true)
Refueling
So we'll get some gas.
Now let's assume that the tank is worth 90 and distance is again 350.
The first evaluations would give us:
if(false && true)
Refueling
When looking at our table, we see that false and true are evaluated as false, so we will not
perform the gasoline refueling.
It is easy to recall the conjunction; it is only true when both expressions are true. We can
remember the rule or simply have an impression of the table at hand. We must remember that
two expressions are needed, one on the right and the other on the left. With only one expression,
it is not possible to do this.

The Use of Disjunction


For the disjunction, we use the operator or. It also needs two expressions, one on the right side
and one on the left side. This disjunction has the following truth table:

P Q P || Q
true true true
false true true
true false true
false false false

Let's look at an example with the disjunction. We have to take the umbrella if it rains or if there's
a lot of sunshine. The expression could look like this:
if(rain == true || lots of sunshine == true)
Take umbrella
Suppose there's rain but no sun, we'd have the expression:
if(true || false)
Take umbrella
In this case, if we look at the truth table, we can see that the result of evaluating the expression
gives us the truth, so we should take the umbrella.
Now let's see what happens if there is no rain and no sun. The expression would look like:
if(false || false)
Take umbrella
In this case, the expression is evaluated as false, and the umbrella is not taken.
It is easy to remember the truth table of disjunction. This is true when any of the expressions is
true. Since if one is true or the other is true, then the total expression is true. It's also nice that we
have this table on hand until we learn the memory disjunction.

The Use of Negation/Denial


We need to meet one more operator, and that is the denial/negation. This operator is very simple
and only needs to make use of only one expression on the right side. With these given
conditions, this expression will be denied by the operator.

p Negation
true false
false true

This means that if the right side operand is true, the operator returns false. And if the right-hand
operand is false, the operator returns true.
Let's look at an example to understand this better.
We have a room with an electric light bulb and suppose we have to turn on the light in the room
when it is not daylight. Then our expression looks like this:
if(!adi == true)
Turn on the light
Let's see what happens when the expression adi has as its true value. The expression adi == true
is evaluated as true and then denied, which in the end results in a false value. As if it receives the
value false, the command or method to turn on the light will be executed.
But if adi is false, then the expression adi == true is evaluated as false, which is denied, and the
If receives true. As the If is set to true, the light is turned on.
Now we can look at an example of how to make use of a logical expression. We can apply this to
our math operations program. We can observe that division must be done when the user has
selected among the options presented, the number 3, and the divisor has a value other than zero.
This is a case in which we can make use of the conjunction. If we proceed to modify the
application to do this, our flowchart should be modified, looking similar to the form we see
below:
We can see how the logical expression is inside the rhombus in the condition of the division.
The program code would look like this:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// Required variables
float a = 0.0f;
float b = 0.0f;
float result = 0.0f;
string value = "";
int option = 0;
// We show the menu
Console.WriteLine("1 - Sum");
Console.WriteLine("2- Subtraction");
Console.WriteLine("3- Division");
Console.WriteLine("4- Multiplication");
Console.Write("What operation do you want to do:");
value = Console.ReadLine();
option = Convert.ToInt32(value);
// We ask for the first number
Console.Write("Give me the first number:");
value = Console.ReadLine();
a = Convert.ToSingle(value);
// We ask for the second number
Console.Write("Give me the second number:");
value = Console.ReadLine();
b = Convert.ToSingle(value);
// We check for sum
if (option == 1)
result = a + b;
// We check for subtraction
else if (option == 2 )
result = a - b;
// We check for division else if (option == 3 && b! = 0)
// Here we use an expression logic result = a / b;
// We check for multiplication
else if (option == 4)
result = a * b;
// We show the result
Console.WriteLine("The result is: { 0}", result);
}
}
}
Let's see another example. Suppose we have to make a program that tells us if a person can drive
a car, and the conditions for driving it are that they are over 15 or 18 years old and that they have
permission from their parents. If we look at the problem, we see that we need two variables, one
for age and one for parental permission. The logical expression could be of the following form:
if (age> 18 || (age> 15 && permission == true))
Can drive
We see that in this case, we use a more complex expression. As with arithmetic expressions, we
have used parentheses to help us and make the logic easier to read. Our expression is a
disjunction, on the left side of the gold we have age> 18, on the right side we have an expression
(age> 15 && permission == true). The second expression is a conjunction and must be evaluated
first. The result obtained will be used by the disjunction. Now we can make the example program
for this expression. First, let's look at the flowchart below:

As in the previous case, we must place the expression within the rhombus regardless of its
complexity.
The program could look like this:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application her e
static void Main(string[] args)
{
// Required variables
int age = 0;
bool permission = false;
string value = "";
// We get the data
Console.Write("Give me the age:");
value = Console.ReadLine();
age = Convert.ToInt32(value);
Console.Write("You have parental permission (true / false): ");
value = Console.ReadLine();
permission = Convert.ToBoolean(value);
// We verify that the rule is fulfilled
if (age > 18 || (age > 15 && permission == true))
Console.WriteLine("It is possible to drive");
else
Console.WriteLine("You can't drive");
}
}
}
Denial simply swaps true for false and false for true. It is easy to remember. The value of the
right-hand operand is inverted. We must not forget that this operator only needs one operand,
and it is always on the right side. Failure to do so may cause problems with our program.
When we have complex expressions, to avoid errors, it is useful to make a truth table of the
expression and test all its cases. In this way, we can see if it works as we expected. The truth
table should be similar to the ones we have used, and we can lean on it to find the final value of
the expression.
Now we will learn to use another selective structure.

The Use of Switch


In one of the previous examples, in which we performed the mathematical operations, we have
observed that for each operation, we must use an if. This is correct, and on several occasions, we
will see that it is necessary to take different options depending on the value of a variable.
As this can happen frequently, we have a selective structure that helps us and allows us to place
the code for these cases easily. This structure is known as a switch. For this, we need a variable
and several cases. For example, in the operation program, each operation is a case. The value of
the variable is compared to a value for each case. If the value matches, then the code starts
running from that line.
When we use the switch, it is necessary to put between parentheses the variable that we use to
carry out the comparisons. Then we have to create a code block and put inside it the cases and
the code to be executed for each case. To indicate a case, we use a case followed by the
comparison value and a colon.
There is a case called default, which we can use if we wish. This case should always be the last
case defined. When the comparison variable has not found its value in any of the cases, then the
code of the default case is executed. In the cases, we can place any valid C# code.
To indicate where the code of a case ends, we must use a break that will allow us to leave the
execution of a selective or repetitive structure. We'll look at this in more detail in another
chapter. If we do not use a break and the case is empty, then the program will continue executing
the code of the next case and so on until the end of the code block that belongs to the switch.
A switch can be represented in the flow chart by the rhombus. Inside it, we place the comparison
variable, and from the corners or sides, we can take out the different execution paths it may have.
As an example, we will modify the program of the arithmetic operations to make use of the
switch. The comparison variable will be the option variable since the value of it will be
compared for each operation.
In this case, the different routes of execution of the switch leave the sides and corners of the
rhombus.
The program code will be as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// Required variables
float a = 0.0f;
float b = 0.0f;
float result = 0.0f;
string value = "";
int option = 0;
// We show the menu
Console.WriteLine("1 - Sum");
Console.WriteLine("2- Subtraction");
Console.WriteLine("3- Division");
Console.WriteLine("4- Multiplication");
Console.Write("What operation do you want to do:");
value = Console.ReadLine();
option = Convert.ToInt32(value);
// We ask for the first number
Console.Write("Give me the first number:");
value = Console.ReadLine();
a = Convert.ToSingle(value);
// We ask for the second number
Console.Write("Give me the second number:");
value = Console.ReadLine();
b = Convert.ToSingle(value);
switch (option)
{
// We check for sum
case 1:
result = a + b ;
break;
// We check for subtraction
case 2:
result = a - b;
break;
// We check for division
case 3:
if (b!= 0) // this if is nested
result = a / b;
else // This else belongs to the second if
Console.WriteLine("Invalid Divider");
break;
// We check for multiplication
case 4:
result = a * b;
break;
// If none of the cases is fulfilled previous
default:
Console.WriteLine("Option not valid");
break;
}
// We show the result
Console.WriteLine("The result is: { 0}", result);
}
}
}
With this we have seen the basic selective structures in C # and how we can use them.
With the switch, we can compare a variable against different values. The variable can be of type
integer or string. The case value must be appropriate for it to work properly. From our analysis,
we know the possible values for each case. The type of comparison variable will depend on the
particular algorithm.
To avoid errors in the switch, we must remember that all cases must end with break or return. If
we don't do it this way, the compiler can give us problems. The use of return will be learned in
the functions chapter. It is good to have well-defined cases to avoid logic problems.
Selective structures help us to make decisions. We have several of these structures: if, if-else and
switch. We can make use of relational and logical expressions in if. This allows us to precisely
indicate the condition that must be met for a certain code to be executed. The use of else allows
us to have code that can be executed when the condition is not met. To compare a variable
against different values and execute a particular code when its content is equal to a certain value,
we use the switch. It is important not to forget the use of the break at the end of the code of each
case.
Chapter 4
Creating Loops

In real life, we sometimes repeat the same activity many times. Also, in computer programs, we
will see that it is necessary to repeat something many times. For this, we will make use of the
loops, which will make our code simpler while we can repeat an activity as many times as
necessary.

The For Loop


The first loop we will learn in this chapter is called the For loop, but to better understand it, we
need to see a problem where it needs to be used. Let's imagine that we have to create a program
for a school, and this program must average out the grades for three students. If we remember,
the average is calculated by adding up all the amounts, and the result of the addition is divided
by the number of amounts we have added. The program is simple since there are only three
students in the classroom.
The diagram for solving this program is shown in the following figure:
The source code looks like this:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// Required variables
float cal1 = 0.0f, cal2 = 0.0f, cal3 = 0.0f;
float average = 0.0f;
string value = "";
// We ask for the dat a
Console.WriteLine("Give me the first grade:");
value = Console.ReadLine();
cal1 = Convert.ToSingle(value);
Console.WriteLine("Give me the second grade:");
value = Console.ReadLine();
cal2 = Convert.ToSingle(value);
Console.WriteLine("Give me the third grade:");
value = Console.ReadLine();
cal3 = Convert.ToSingle(value);
// We calculate the average
average = (cal1 + cal2 + cal3) / 3;
// We show the average
Console.WriteLine("The average is {0}", average);
}
}
}
We can see that the program is very simple. We ask for three values and calculate the average. In
the end, we simply display the result. There is no problem with the program; in fact, it is correct.
Now imagine that the school wants the average for a group of five students. This is not difficult;
we could simply add two more variable requests and modify the formula. This doesn't seem to be
a problem, but what if the group is fifteen students? This solution of adding more requests,
although feasible, is not comfortable. What if we are asked to average for the whole school with
2500 students? Then it is clear that we cannot continue with this type of solution.
However, from this problem, we can observe something. All requests for grades are made in the
same way, and asking for grades is something we have to repeat many times. When we have
code that must be repeated several times, we can use the For loop. This allows us to repeat the
execution of a code a certain number of times.
Before we solve our problem with the loop, the first thing we have to do is learn how to use the
loop. The loop statement starts with the keyword for the next parenthesis. Inside the parentheses,
we will place expressions that serve to control the loop. The For loop has four main parts:
for (initialization; condition; increment)
code
The For loop will need one or several control variables, although in most cases, we will use only
one variable. Let's look at the different parts of the For loop. First, we find the initialization. In
this section, we give the control variable its initial value. The initial value is carried out through a
normal assignment, such as the ones we have worked on. The second section carries a condition
in the form of a relational expression. This is used to control when the loop ends, and here we
generally indicate the number of turns that the loop takes.
Then we have the code. In this section, we put the part of the code that we want to repeat. This
section can be a statement or a block of code. Finally, we run the increase section. Here we
indicate how the value of the control variable will be modified for each turn of the loop.
When the For loop is executed, the first thing that is done is the initialization and then the
condition. If the condition is true, then the code is passed and then the increment. After the
increment, we go back to the condition and repeat the process. If the condition is not fulfilled,
then we say that the loop
We can see this well in the following flowchart.
Being able to understand the For loop requires a lot of experimentation, so we will do several
tests to know its main characteristics.
Let's start with a simple program. We will use the loop to display a message, which will only
print the value of the loop control variable. To know what work the loop does, we will place a
message before and after the loop.
Being able to understand the For loop requires a lot of experimentation, so we will do several
tests to know its main characteristics.
Let's start with a simple program. We will use the loop to display a message, which will only
print the value of the loop control variable. To know what work the loop does, we will place a
message before and after the loop.
To start easily, we want the loop to run ten times. Let's first look at the program and then look at
each part of the loop. Our program is as follows:
Before running the program, let's see how it is built. We first declare our control variable. This is
called n. The program will print the numbers from 1 to 10, and n will change its value as the loop
repeats.
Inside the For loop, we immediately find that n is assigned the value 1. This means that our count
will start with number 1. If we wanted to start at another value, this is where we would assign it.
Then we have the condition. The condition limits how far we will have n. In this case, it is up to
10. As long as n has a value less than or equal to 10, the message is displayed.
Since, in this case, 1 <= 10 is true since n is 1, then the message is written. The message is very
simple since it simply shows the value contained in variable n. After this, we go to the increment.
Incrementing increases the value of n by one. After the first increment, n will be 2. This is
repeated, and the value of n is incremented by 1 each time the loop is repeated. In the last
increment, n will have the value of 11, and in this case, the condition will no longer be met, and
the loop ends. Let's see the execution of the program, and we will observe how n changes its
value, and indeed the loop is carried out only 10 times.

Here we can see how the loop was repeated, and the value of n was modified in each turn.

The Start Value


Now we can start experimenting with the loop. The first thing we'll do is set the start value of the
loop and see how the execution of the program is modified. This is useful since it is not always
necessary to start counting from 1, sometimes we need to start counting from other numbers.
Let's suppose that we now have to count from 3 to 10. To do this, we simply modify the start
value in the loop initialization section:
for (n = 3; n <= 10; n = n + 1)
Console.WriteLine("{0}", n);
Let's run the program.

This is the result. Indeed, the control variable starts with 3. Of course, the number of repetitions
is less.
The control variable may have a negative value at initialization. This is useful when we need to
count from a negative number. Let's modify the For loop code as follows:
for (n = -10 n <= 10; n = n + 1)
Console.WriteLine (“{0}”, n);
The execution gives us the result that we can see in the following figure.
We can see that the path starts at -10. It should not be overlooked that the control variable also
passes through the value of zero.

The Count Limit Loop


We can also control how many numbers to count. Let's see our code to count from 1 to 10.
for (n = 1; n <= 10; n = n + 1)
Console.WriteLine (“{0}”, n);
In this example, we could see that the count limit is being controlled in the condition and that
there is no single way to write it. We can see that the following condition n <= 10 could also be
written as n <11 without affecting in the least the execution of the loop.
for (n = 1; n <11; n = n + 1)
Console.WriteLine (“{0}”, n);
Let's see the result of this change in the figure below.
We can see that although the condition is different, what we want is still fulfilled.
This should be taken into account to avoid confusion in the future, especially when we see other
people's code using a different style than ours. Now let's modify the loop to count from 1 to 15;
in this case, we will use the < operator instead of <=.
for (n = 1; n < 16; n = n + 1)
Console.WriteLine ("{0}", n);
Let's run the program and see how it behaves.
In this case, we have increased the range of the loop.

Incremental Control
Now that we know how to place the range of the For loop from its start value to the value it will
count at, and we can start learning how to make use of the increment. Our increase has been one
at a time. However, we can make the count two by two, three by three, or any other value.
To accomplish this, we simply have to modify the increment and indicate how our control
variable would be increased. The value of the increment can be an explicitly placed value or the
value inside a variable. For example, let's make our loop advance by two.
for (n = 1; n <16; n = n + 2)
Console.WriteLine (“{0}”, n);
As we can see, we have now placed n = n + 2. With this, we indicate that 2 will be added to the
value of n with each turn of the loop. This is easier to understand if we look at the execution of
the program and see the display of the values of n.
We can see that the value of n increases by two for each turn of the loop.
The loops that we have used have always counted progressively, from the lowest value to the
highest value. But it is also possible to make a regressive loop. For example, we could make the
loop count from 10 to 1. For this, we need to modify not only the increment but also to put the
correct expressions in the initialization and the condition.
Let's see how to achieve this with the following statement:
for (n = 10; n>=1; n = n - 1)
Console.WriteLine(“{0}”, n);
Here we can observe how the value of n decreases one by one.

The Counter and the Accumulator


Now we will learn two new concepts. There are two categories of variables depending on how
they store the information, and firstly we have the counter. The counter is a variable that will be
increased or decreased one value at a time. In most of the examples above, it has not worked as a
counter. For its part, the accumulator is a variable that can increase or decrease its value by any
number.
We have not yet made use of an accumulator, but we will see when we must resolve the problem
of the students' averages.
For now, let's look at a small example of these two variable classifications explained so far:
We have created two variables: counter and accumulator. The counter variable increases its value
one by one. On the other hand, the accumulator variable will increase its value based on the
number contained in the counter.
Next, to understand better what has been explained, let's run the program and see how the two
variables work:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// Required variables
int n = 0; // control variable
int counter = 0, accumulator = 0;
Console.WriteLine("—- Before loop —-");
for (n = 10; n >= 1; n = n - 1)
{
counter = counter + 1;
accumulator = accumulator + counter;
Console.WriteLine("{0}, {1}", counter, accumulator);
}
Console.WriteLine("—- After loop —-");
}
}
}
We have created two variables: counter and accumulator. The counter variable increases its value
one by one. On the other hand, the accumulator variable will increase its value based on the
number contained in the counter.
Next, to understand better what has been explained, let's run the program and see how the two
variables work:
We see how the values of the variables change with each turn of the loop.

Increases and Decreases


When we work the C# with the For loop, commonly, we have to increase or always decrease one
by one. To facilitate this, we have new operators that are the increased operator and the decrease
operator.
Operator Sign
Increase ++
Decrease -
These operators can be used as suffixes or prefixes in the variable. In the case of suffixes, we
write it as variable++ and for the prefix as ++variable. The value contained in the variable in
both cases will be increased by one. What changes is how the expression contained in the
operators is evaluated.
When we have the case of the suffix, the expression is evaluated with the current value of the
variable and then incremented to the variable. In the case of the prefix, the value of the variable
is first incremented, and then the expression is evaluated.
This may not be very clear in the first explanation, but we should not worry about it. To
understand this, we will see an example below:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
int number = 5;
Console.WriteLine("Initial value {0}", number);
// we increase
number++;
Console.WriteLine("After increment {0}", number);
// We decrease number -;
Console.WriteLine("After decrement {0}", number);
// Increase in sentence
Console.WriteLine("Increment in statement {0}", number++);
Console.WriteLine("Value after statement {0}",
number) ;
// Increment in statement as prefix
Console.WriteLine("Increment in statement {0}", ++number);
Console.WriteLine("Value after statement {0}",
number);
}
}
}
We can run the written code and see what has happened, and why we get those values displayed.
Here we see the values obtained by the operators and the difference in using them as suffixes or
prefixes.
We start with a variable called number to which we assign the initial value of five. We display its
value on the screen. Then we use the operator and increase the value of the variable. In this case,
it is worth 6 since the increment is in one. We check this when we print the value of the variable.
Then we carry out the decrease. In this case, the number keeps the value of 5 since we have
decreased it by one. The printing of the message shows us that we are correct.
Now that we have seen how it works, we can try to place the operator inside a statement. The
statement will be the same message that we want to display to see how it is evaluated and the
differences between the usage as a suffix and a prefix. Let's not forget that the last value in the
number is 5. This increases the value to 6, but if we look at the program execution, the value that
appears is 5.
We already know the reason: when used as a suffix, the expression is evaluated with the current
value and then increased. The following impression of the value of the variable shows us how
effectively the variable was increased after the previous statement. Now we can experiment with
the suffix. Our current value is 6, and we enter the statement. In this case, first, the value is
increased, and we have 7 in the number variable, and then we print it. So, in this case, we get 7
on the screen. With this, we have already seen the behavior of these operators, and we can
integrate them into our For loop in the case of increment:
for (n = 1; n <16; n++)
Console.WriteLine(“{0}”, n);
Or to decrease its value:
for (n = 10; n> = 1; n—)
Console.WriteLine (“{0}”, n);
There are other operators that we can also use when we want to calculate a value with the
variable and save the same value in the variable.

Operator Example Equals


+= number + = 5 number = number + 5
-= number- = 5 number = number-5
*= number * = 5 number = number * 5
/= number / = 5 number = number / 5

These operators also allow us to modify the value of the variable.


It is good to know these operators since we will see them and we will have to use them
frequently in many computer programs. For example, to increment from five to five in a For
loop, we do the following:
for (n = 1; n <16; n + = 5)
Console.WriteLine (“{0}”, n);

Examples With the For


Now we can solve the problem of calculating the average. We know what needs to be repeated
and how many times we need to do it. In this case, what should be repeated is to ask for the
student's grade and to make a sum of these grades. The number of times it has to be repeated
depends on the number of students. This sum of the grades can be done with the cumulative
variable. The final average is calculated by dividing the accumulator by the number of students,
and it is displayed on the screen. Let's see the flowchart of our algorithm to solve this problem.
We can easily observe the For loop and what is done within it.
Now we can see how the program code looks:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
int quantity; // Number of student s
Console.WriteLine("Give me the number of students:");
string value = Console.ReadLine();
quantity = Convert.ToInt32(value);
// Required variables
int n;
// Loop to capture grades
for (n = 1; n <= quantity; n++)
{
Console.WriteLine("Give me the student's grade");
value = Console.ReadLine();
float calif = Convert.ToSingle(value);
// We carry out the sum of qualifications sum + = grade;
}
int average = 0;
// We calculate the average average = sum / quantity;
// We show the average
Console.WriteLine("The average is {0}", average);
}
}
}
If we run the program we get the output shown in the following figure.

We can see how the request for the rating is repeated the number of times indicated.
An important point about this program, compared to the first attempt we made at the beginning
of the chapter, is that it can work with any number of students. It doesn't matter if it's 5, 10, or
5000; the program will do its job. We see how using the loop not only gives us flexibility but
also prevents us from having to repeat a lot of code.
Let's look at another example. We can use the For loop in any problem that needs something to
be repeated: an operation, a count, some process. But also the number of repetitions must be
known, either by an explicitly placed value or a value placed inside a variable.
Now we have to calculate the warp of a number. For example, the factorial of 5 is 5*4*3*2*1,
which gives 120. Similarly, we must calculate the factorial value of any number given by the
user. If we look at the problem and how it is solved, we can see that there is a loop, and this loop
is counting down. We can easily solve it with a for-loop that carries out the multiplication with
the control variable as the product.

This is the flow chart of the algorithm for calculating the factorial of a number.
The program code looks like this:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// Required variables
int n = 0; // Control variable
int number = 0; // Number to which we take factorial
int factorial = 1; // Factorial calculated
string value = "";
// We ask for the number
Console.WriteLine("Give me the number to get the factorial from:");
value = Console.ReadLine();
number = Convert.ToInt32(value);
// We calculate the factorial in the for loop (n = number; n> = 1; n) factorial
* = n;
// We show the result
Console.WriteLine("The factorial of {0} is {1}", number, factorial);
}
}
}
When we run the program, we find that we can carry out the factorial calculation without any
problem.
The factorial of the number is properly calculated.

The Do-While Loop


We have seen that the For loop is very useful for repeating something when we know the number
of repetitions previously. However, sometimes it is not possible to know the number of
repetitions we will have. Let's think that a carpenter has hired us to make a program that
transforms from feet and inches to centimeters since they use it to calculate the size of the tables.
The program is very simple, but we cannot leave it like that since it would be very uncomfortable
for them to run the program every time they need to cut.
We think that this can be solved with a For loop. How many turns the loop? If we put 10 laps, we
can think that it is enough. But some days need 15 conversions, and you need to run the program
twice. And on the days that only need 5 conversions, they have to write 5 more just to end the
program.
We can deduce from the problem that we actually need a loop. However, we do not know the
number of repetitions previously, so the For loop is not adequate. We need a loop that can be
controlled by a condition, and the evaluation of this condition will depend on the state of the
program at any given time.
The do-while loop allows us to do this. It allows a certain code to be repeated while a condition
is evaluated as true. The value of the evaluation will depend on the status of the program at any
given time.
The do-while loop is coded as follows:
do {
Code
}(condition);
If we look at the flow chart below, we can see the internal workings of the do-while loop simply
and clearly.

This is the diagram of the do-while loop. We can observe its internal behavior.
Let's start cycling through the loop. First, we find the code to be carried out. This code is defined
inside a code block, even if it is only a statement. Generally, the code will modify in some way
the value of the variable or variables that we use for the expression in the condition. This value
change can be carried out through a calculation, process, or even a request to the user. Then we
have the condition to evaluate. In the condition, we place a logical or relational expression. If,
when evaluating the condition, we obtain the value true, then the code is repeated. In case the
false value condition is no longer repeated, and the program is continued. Keep in mind that
sometimes it happens that the condition is evaluated as false from the first time. In this case, the
code will only have been run once.
Let's see an example. We will create the carpentry program and use the do-while loop so that the
program repeats as many times as necessary, even without knowing how many times it is. To
achieve this, we have to think carefully about our condition and what is the state of the program
that we will evaluate in it.
The easiest way to do this is to ask the user if they want to do another conversion. If he does, the
code to convert is repeated. In case the user does not want it, the program ends. In this way, the
repetition of the loop is controlled and can be repeated, even without knowing how many times it
has to be done. Our program will have the following flowchart.
Here we can observe the programming and distinguish the do-while loop.
The program will be as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// Required variables
float feet = 0.0f; // number of feet
float inches = 0.0f; // number of inches
float centimeters = 0.0f; // Result in centimeters
string response = ""; // Answer for another calculation
string value = "";
do
{
// We ask for the feet
Console.WriteLine("How many feet:");
value = Console.ReadLine();
feet = Convert.ToSingle(value);
// We ask for inches
Console.WriteLine("How many inches:");
value = Console.ReadLine();
inches = Convert.ToSingle(value);
// Convert to centimeters = ((feet * 12) + inches) * 2.54f;
// We show the result
Console.WriteLine("They are {0} centimeters", centimeters);
// We ask if another conversion
Console.WriteLine("Do you want to do another conversion (yes /
no)?");
response = Console.ReadLine();
} while (response == "yes") ;
}
}
}
In the execution, we can verify that we have a loop, but it can end whenever we want.
We can see that we have placed inside the loop the part of the conversion from feet and inches to
centimeters. After showing the result, we ask the user if he wants to make another conversion. If
so, we repeat the loop. If the user does not wish to make another conversion, the loop ends. This
allows us sometimes to repeat five times, when necessary ten, and so on depending on the user's
needs. We have solved the problem.
The do-while loop gives us extra flexibility, but it is always necessary to use the right type of
loop for the problem we have.
Let's look at another example where we can use this loop. In one of the previous programs, we
asked the user what operation he wanted to perform, and then we asked for the operands. The
program as it is is only executed once, but if we use the do-while loop and put a new option in
the menu, then the user can perform the operations that are needed or only one as it was used
before. This kind of behavior is very useful and easy to implement with the
If we modify the program, it will look like this:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application her e
static void Main(string[] args)
{
// Required variables
float a = 0.0f;
float b = 0.0f;
float result = 0.0f;
string value = "";
int option = 0;
// We have the loop
do
{
// We show the menu
Console.WriteLine("1 - Sum");
Console.WriteLine("2 - Subtraction");
Console.WriteLine("3 - Division");
Console.WriteLine("4 - Multiplication");
Console.WriteLine("5 - Exit");
Console.Write("What operation do you want to do:");
value = Console.ReadLine();
option = Convert.ToInt32(value);
if (option!= 5)
{
// We ask for the first number
Console.Write("Give me the first number:");
value = Console.ReadLine();
a = Convert.ToSingle(value);
// We ask for the second number
Console.Write("Give me the second number:");
value = Console.ReadLine();
b = Convert.ToSingle(value);
switch (option)
{
// We check for sum
case 1 :
result = a + b;
break;
// We check for subtraction
case 2:
result = a - b;
break;
// We check for division
case 3:
if (b!= 0) // this if is nested
result = a / b;
else // This else belongs to the second if
Console.WriteLine("Invalid Divider");
break;
// We check for multiplication
case 4:
result = a * b;
break;
// If none of the previous cases is fulfilled
default:
Console.WriteLine("Invalid option");
break;
}
// We show the result
Console.WriteLine("The result is: {0}", result);
}
} while (option!= 5);
}
}
}

The While Loop


Having understood the Do-While loop, we can see another type of loop. This loop is known as
While, and in some way, it is similar to the previous one, but it has its own characteristics that
we must know to use it correctly. The while loop can also be used when we have something to
repeat, but we don't know the number of repetitions previously. The repetition of the loop has to
do with the fulfillment of a condition. Unlike the do-while loop, this loop may not be executed
even once. Its structure is as follows:
while (condition) {
Code
}
To understand how it works, let's look at the flowchart.
This loop starts with one condition, and we must take this into account in our algorithms.
If we look at the flowchart, the first thing we find is a condition. In this condition, we will place
a logical or relational expression. If the condition is evaluated as true, then we proceed to execute
the code. After the code, we return to the condition. If the condition is not met, then the code is
not executed, and the rest of the program continues.
Having the condition at the beginning of the loop brings us to an important point. If the condition
is not met from the beginning, then the loop is never carried out. If our algorithm is well
designed, this is desirable.
Now we can make an example program that uses the while loop. In this example, we will use the
feature of the loop that can be repeated or not repeated even once. Imagine that we have to make
a control program to cool a boiler. The boiler must be cooled to 20 degrees Celsius.
The while loop will be used to reduce the temperature one by one for each turn of the loop until
we reach 20 degrees centigrade. The advantage that this loop gives us is that if the temperature is
less than 20 degrees, you do not even enter the loop, and no cooling takes place. In this case, we
take advantage of the properties of the loop. Let's look at the code of this program:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Start the application here
static void Main(string[] args)
{
// Required variables
int temperature = 0;
string value = "";
// We ask for the temperature
Console.WriteLine("Give me the current temperature:");
value = Console.ReadLine();
temperature = Convert.ToInt32(value);
// The loop reduces the temperature
while (temperature > 20)
{
// We decrease the temperature;
Console.WriteLine("Temperature -> {0}", temperature);
}
// We show the final temperature
Console.WriteLine("The final temperature is {0}", temperature);
}
}
}
To check that the loop does indeed act as we have said, we must run the program twice. The first
time we will set the temperature higher than 20°C. This should make the loop run. The second
time we will set a value lower than 20. In this case, the program should not enter the loop.
Let's see the result of the first execution:
We can observe that the loop has been entered and that it is carried out while the temperature is
higher than 20°.
If we carry out the second execution, we get the following:
In this case, the loop is not entered during program execution.
With this, we have seen the three main loops available in C# and how we can use them within
our developments.

Some Important Notes


Loops That Start at Zero
In C #, we will see that in many cases, we have structures with zero indexes. This means that its
first element is considered in position 0, not in position 1. Although it seems strange to us to start
counting from scratch, on the computer, it is very common for this to happen, so it is convenient
for us to get used to creating loops of this form.

Problems With the For Loop


One of the most common problems with the For loop is mixing the number of necessary
repetitions. Sometimes it happens that the loop goes one more turn than we want. If this happens,
the first thing to check is the condition. A poorly written condition will prevent the desired
repetitions from taking place. Another problem may be positioning; at the end of for.
Initialization of Variables in Loops
If we carry out the declaration and initialization of a variable inside the code block of a loop, the
variable will be initialized every time the loop is repeated and will not keep its value between
turns of the loop. This detail can also lead to logic errors, so you have to decide carefully where
the variable is declared.
Problems With Variables in the Loops
If we carry out the declaration of a variable inside the loop code block, it can only be used in that
loop. If we try to use it after the loop, it will not be recognized by the program. If this is the case,
it is best to declare the variable at the beginning of the function so that it is known in it.
Verify Changes in a Program
In the math operations program, we have added a do-while loop. However, our work does not
end there. We have to run it to see if it behaves in the desired way. So we needed to add an If,
since otherwise, it would ask us for the operators even when what we wanted was to exit.
Guarantee the Execution of the While Loop
Some programmers use the while loop, and to guarantee its execution, they assign values to the
variables so that the condition is fulfilled at the beginning. This is recommended in a few cases.
If we need a loop that guarantees input, it is better to use do-while instead of forcing our logic
with the While loop.
Nested Loops
As with the If loop, it is possible to have nested loops. As inside the loops, we can put any valid
code, so we can also put another loop. When one loop is inside another, we say they are nested.
Great care must be taken with control variables and conditions to avoid logic problems.
Loops allow us to repeat the execution of certain code. The For loop is used to repeat something
a certain number of times. This loop requires a control variable with an initial value, a condition,
and an increment. The do-while loop allows us to repeat a certain code an unknown number of
times and is executed at least once. The number of times depends on the condition. The while
loop also allows us to repeat the code an unknown number of times, but in this case, the loop
may or may not be executed depending on its condition.
Chapter 5
The Functions and Methods

Functions and methods are very important elements of programming. In C#, we will be using
them frequently, especially when we move towards object-oriented programming. Functions give
us many advantages and allow us to develop our applications faster and more orderly.

The Functions
Let's get to know the functions. Let's look at an example of a problem and then how using the
function can help us. The function is an element of the program that contains code and can be
executed; that means, it performs an operation. The function can be called or invoked when
necessary, and then the code inside it will be executed. Once the function is finished, the
program continues in the next instruction from which it was called.

We can observe how the execution of the program goes to the function and then returns to the
next sentence from where it was invoked.
The functions, to be useful, must be specialized. In other words, each function must do only one
thing and do it well. We have already used one function, it's the Main() function, and we can
create more functions as we need them. Within object-oriented programming classes have code,
and this code is found within functions called methods. For example, when we have converted
from a string to an integer, we make use of a function called ToIn32() that is inside the Convert
class.
The functions consist of five parts:
modifier type Name (parameters)
{
code
}
We will see the five parts now, but as we study the functions, we will know how they are used.
Functions can return information, and this information can be string, integer, floating, or any
other type. In the type section, we have to indicate precisely what kind of information is being
returned. If the function does not return any value, then we have to indicate its type as void.
All functions must be identified, and we do so by their name. The functions that we place inside
the classes must have a unique name. The name is also used to invoke or execute the function.
Functions may need data or information to work. We don't give this information through their
parameters. Parameters are nothing more than a list of variables that receive this data. If the
function doesn't need to use the parameters, then we can simply leave the brackets empty. We
should never forget to place the parentheses even if there are no parameters.
The code of the function is placed inside a block of code. In this section, we can place any valid
C# code, that is, variable declarations, cycles, selective structures, and even function invocations.
Functions, when declared, can have a modifier before the type. Modifiers change the way the
function works. We will be using a modifier known as static. This modifier allows us to use the
function without having to declare an object of the class to which it belongs.
We have four basic types of functions: those that only execute code, those that return values, and
those that receive parameters and receive values. During this chapter, we will get to know them.
Now that we know the basic elements of the functions, we can see an example of where their use
would be appropriate. Suppose we have a program in which, in different sections, we have to
write the same code, but due to its logic, we cannot use a cycle since it is in different parts of the
program. In this case, our only solution so far would be to rewrite the code simply.
Another way to solve it and avoiding repeated code is to use the function. The code that is going
to be used repeatedly is placed inside the function, and every time we need to use it, the function
is simply invoked. In our example of the carpenter, which we analyzed in the previous chapter,
we are in charge of making conversions from feet and inches to centimeters. The conversion was
done with a simple but rather long formula.
If now our carpenter needs a program to transform the measurements of a complete table into
centimeters, then we would have to use the right formula in several places. In order not to copy
the same code several times, the most convenient thing would be to place the formula in a
function and simply invoke it where necessary. Let's start to learn how to program and invoke
functions.

Functions That Execute Code


The first type of functions we're going to know are those that execute code. These functions do
not receive data and do not return any data. They just perform some operation. Although they
don't seem to be very useful at the moment, they are.
To use the function, we must declare it. The declaration must be made within the code block
corresponding to a class. For the examples discussed in this book, we are using the class called
Program. Our Main() function is also inside this class.
At this point, we will take a programming strategy, which does not yet belong to structured
programming. In the future, we will see object-oriented techniques. In this technique, we use the
Main() function as a logic manager, and most of the process will be carried out in the functions.
We will create an application and place each of the types of functions we are going to learn,
leaving Main() as our program manager. The program is going to be conceptually simple since
what we are interested in is understanding how the functions work.
The program will simply ask the user the type of arithmetic operation we want to perform and
then perform it with the data we provide. This program was already solved before, but in this
case, it will be implemented by adding the use of the functions.
In the flow chart, we indicate the function using a rectangle that has two stripes on the sides.
When we see it, we know that we have to go to the function and execute its code. Let's see how
the flowchart of the application would look like.
Here we can see the flowchart and find the places where the functions are invoked.
We see that our diagram is very simple, and we can also locate immediately the place where we
invoke the functions. Each of the operations will have its own function. At this point, we will not
program everything; we will grow the program little by little.
Let's start by building the program, leaving the administration of the logic to Main(), as it
appears in the flow chart.
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Here starts the application
static void Main(string[] args)
{
// Required variables
int option = 0;
string value = "";
// We show the menu
Console.WriteLine("1 - Sum");
Console.WriteLine("2 - Subtraction");
Console.WriteLine("3 - Multiplication");
Console.WriteLine("4 - Division");
// We ask for the option
Console.WriteLine("What is your option:");
value = Console.ReadLine();
option = Convert.ToInt32(value);
// We check for the sum
if (option == 1)
{
}
// We check for the subtraction
if (option == 2)
{
}
// We check for multiplication
if (option == 3)
{
}
// We check for division
if (option == 4)
{
}
}
}
}
As we see in our Main() function, we have the main logic of the program. At this moment, we
have left the if code blocks empty, and we will add the corresponding code as we go along.
Let's start creating the function for the addition. As this function will not receive any data or
return any values, everything will be done inside. You will be responsible for requesting the
operands, performing the summation, and displaying the result. Then we place the declaration of
the function. We do this after the Main() function, remember to be careful with the { }. We must
also create their flowchart and solve them as usual. The flowchart is as follows.
This is the flowchart of the function; we must also do them.
Our function is as follows:
static void Sum()
{
// Required variables
float a = 0;
float b = 0;
float r = 0;
string number = "";
// We ask for the values
Console.WriteLine("Give me the first number");
number = Console.ReadLine();
a = Convert.ToSingle(number);
Console.WriteLine("Give me the second number");
number = Console.ReadLine();
b = Convert.ToSingle(number);
// We calculate the result
r = a + b;
// We show the result
Console.WriteLine("The result is {0}", r);
}
We can see that the function is static. As the function doesn't return any values, its type is void,
and the function's name is Sum. We choose this name because it describes the activity that the
function carries out. As it doesn't receive any data from the main program, we don't put any
parameters, and the parenthesis is empty. In the code, we have all the steps to solve the sum and
we already know them.
As we can see, it is possible to declare variables. We must know that the variables that are
declared inside the function are known as local variables, and they will only be known inside that
function, so they can only be invocated inside the corresponding function.
With this, the function is ready; however, if we execute the program, nothing different happens.
This is because we have not invoked the function. When we invoke the function, its code is
executed. To invoke a function that only executes code, we simply place its name followed by ()
and semicolon in the place where we want it to be executed. In our case, it would be the if code
block for the sum, as follows:
// We check for the sum
if (option == 1)
{
Sum();
}
Now, if we run the program and select the additional option, we'll see that the function's own
code is actually executed.

In the execution, we can observe how the code of the function is being executed.
Functions That Return a Value
Our next function type can return a value, and this means that when the function is called, it will
perform the execution of your code. The code will calculate a value somehow, and this value
calculated by the function will be returned to whoever invoked the function. The invocation may
have been made by the Main() function or some other function.
Since the function will return a value, we need to indicate its type. The type will depend on the
value returned. If the value is an integer, then the type of the function is int. If the value is a float,
then the function will have type float and so on. The function can return any of the types defined
in the language and also programmer-defined ti-pos and objects of different classes.
The function will use a special command to return the value; this command is known as a return
and is used as follows:
return variable;
As soon as the program execution finds a return, the function is terminated even if it has not
come to an end. At the same time that the function ends, the value co-located after the return is
returned to the one who called. The value can be placed with a variable or explicitly with a
particular value. Do not forget to put the semicolon at the end of the sentence. The end of the
function is carried out even if we have code written after the return.
Since the function returns a value, on the invoker side, we need to have someone who can
receive the returned value. Generally, we will use a variable, but in some cases, it can be an
expression that will be evaluated with the value returned by the function. Suppose our function
returns an integer value. So we can have a code like the following.
int n;
n = function ();
In this way, the value returned by the function is stored in the variable n, and we can make use of
it. We understand the code as follows. We have an integer variable n. Then we have an
assignment for n. If we remember, the assignment is always from right to left. The expression is
evaluated, and the function is executed and calculates a value, which is returned by return. This
value is considered to be the evaluation of the statement and is assigned to n. From this point on,
we can use the value as we need it.
Now we can start using this type of function in our application. For the subtraction operation, we
will make use of it. The code in the Main () part will not be so simple since we not only need an
invocation, we must receive a value and do something with it. In this way, in the if for
subtraction, we will obtain the value returned by the function and then present it to the user. The
Subtraction () function has the following flowchart.
We can see how the diagram of this function is created, not forgetting the return of the value.
The function code is as follows:
static float Subtraction()
{
// Required variables
float a = 0;
float b = 0;
float r = 0;
string number = "";
// We ask for the values
Console.WriteLine("Give me the first number");
number = Console.ReadLine();
a = Convert.ToSingle(number);
Console.WriteLine("Give me the second number");
number = Console.ReadLine();
b = Convert.ToSingle(number);
// We calculate the result
r = a - b;
// We return the result
return r;
}
We can see that the Subtraction () function is of float type, and in the end, we have placed the
return indicating the variable whose value we want to return, in our case r. But not only must we
add the function, but it is also necessary to put new code in the if that corresponds to the
subtraction.
// We check for the subtraction
if (option == 2)
{
// Variable for our result
float result = 0;
// We invoke and obtain the result
result = Subtraction();
// We show the result
Console.WriteLine("The result of the subtraction is
{0} ", result);
}
Let's run the program. We can see that the function acts as expected.

We see how the value returned by the function is displayed in who invoked it, in our case Main
().

Functions That Receive Values


So far, the functions we have used to ask the user directly for the values they need to work.
However, the functions can also receive values at the time they are invoked. This way, they work
with the values passed by the program instead of asking the user for them. These values are
known as parameters. Parameters can be of any type, either native C# types such as integer, float,
string, or programmer-defined types such as classes and structures.
The parameters must have their type and name. The name allows us to access the data it contains,
and in fact, they will work as if they were local variables to the function. Inside the function, we
use them as normal variables. The parameters are defined in the function's declaration. Inside the
parentheses of the function, we list them. The way to list them is first to put them in the type of
name. If we have more than one parameter for the function, then we should separate them by
commas.
The invocation of the function is very simple, and we simply have to put the name of the
function and, between the parentheses, the data that we are going to send as parameters. The data
can be placed using variables or an explicitly placed value.
We can now do the function that will take care of the multiplication. This function will receive
the operands from Main() through the parameters, will perform the calculation, and will show it
to the user. As the Main() function sends the information, it will then be its responsibility to ask
the users for it.
The flowchart of the Multiplication() function is shown below.

The Multiplication() function is simpler, as it does not ask the user for data directly.
The function code is as follows:
static void Multiplication (float a, float b)
{
// Required variables
float r;
// We calculate the value
r = a * b;
// We show the result
Console.WriteLine ("The result is {0}", r);
}
As we can see, the function will have two parameters. The parameters are of the floating type
and are called a and b. Let's not forget that they are separated by a comma. The parameters a and
b will work as variables, and their content will be the values passed in the invocation.
The other place where we must add code in the Main() function, in this case, the if for
multiplication.
// We check for multiplication
if (option == 3)
{
// Required variables
float n1 = 0;
float n2 = 0;
string number = ””;
// We ask for the values
Console.WriteLine ("Give me the first number");
number = Console.ReadLine ();
n1 = Convert.ToSingle (number);
Console.WriteLine ("Give me the second number");
number = Console.ReadLine ();
n2 = Convert.ToSingle (number);
// We invoke the function
Multiplication (n1, n2);
}
Inside the If we create two floating variables and ask the user for the variables, we are going to
work with. These values are stored inside the variables n1 and n2. Now let's see the function
invocation. As the function was defined to receive parameters, then we must pass data in its
invocation. The parameters are placed between the parentheses. As we have it, the parameter a
will receive a copy of the value contained in n1, and the parameter b will receive a copy of the
value contained in n2. Now the function can carry out its work. The variables used in the
invocation don't need to be called like the parameters declared in the function. If needed, the
invocation could carry an explicitly placed value, for example:
// We invoke the function
Multiplication (n1, 4.0f);
When the function is invoked, the parameter a receives a copy of the value contained in n1, and
the parameter b receives the value of 4.
We see that the function prints the correct result, which shows us that it is receiving the
information passed on the parameters.

Functions That Receive Parameters and Return a Value


We have already seen three different types of functions, and surely we have already understood
how they work. We can easily imagine what this type of function will do. This function will
receive information from whoever invokes it. The information is passed through parameters. The
function performs some action or computation and gets a value that is going to be returned. The
returned value is received at the place where the function was invoked and can be worked with.
The parameters will be used as variables, and we declare them inside the parentheses of the
function. We have to indicate the type that will receive, followed by its name, and if we have
more than one parameter, then we must separate them by commas. Since the function returns a
value, it is necessary to indicate its type in the declaration. The variable that will receive the
returned value should preferably have the same type as the function or at least one type that is
compatible or possible to convert. As always, we will use the return to be able to return the
calculated value. In fact, this type of function uses all the parts of which a function consists.
At this time, we must program the function that performs the division. The function will receive
two floating values, and it will verify that we do not carry out the division by zero; it performs
the calculation and returns the value.
If we turn the flowchart into code, we'll find something interesting:
static float Division (float a, float b)
{
// Required variables
float r = 0;
// We check for division by zero
if (b == 0)
{
Console.WriteLine (“Unable to split
between zero ”);
return 0.0f;
}
else
{
r = a / b;
return r;
}
}
Inside the function, we have two returns. Does this mean that we are going to return two values?
Not really. We can only return a value with this type of function. What happens is that each of
our returns is in a different execution path. Let us observe that one is carried out when the If is
fulfilled, and the other is executed when the if is not fulfilled. For the function, only one of them
can be executed. We can also notice that one of the returns is returning an explicitly placed
value; in this case, 0.0. If we put explicit return values, they must be of the same type as the type
of the function.
This is an important concept that gives us flexibility in our code. We can return under different
conditions, as long as we only have one return per execution path. If our function must return
values and we have several execution paths, for example, several nested if or if, then we must put
a return on each path. It is not possible to leave a route without the possibility of re-entering a
value. We must take into account these characteristics to avoid logic problems within our
program.
On the side of the Main () function, we must also add code. The code will be placed in the code
block that corresponds to the If of the division.
// We check for division
if (option == 4)
{
// Required variables
float n1 = 0.0f;
float n2 = 0.0f;
float result = 0.0f;
string number = ””;
// We ask for the values
Console.WriteLine ("Give me the first number");
number = Console.ReadLine ();
n1 = Convert.ToSingle (number);
Console.WriteLine ("Give me the second number");
number = Console.ReadLine ();
n2 = Convert.ToSingle (number);
// We invoke the function
result = Division (n1, n2);
// We show the result
Console.WriteLine (“The result is
{0} ”, result);
}
As in previous cases, we first declare the necessary variables and ask for the values. Then we
invoke the function. In the invocation, we pass as parameters to our variables n1 and n2. The
execution of the function is carried out, and we receive a value back. This value is assigned to
the result variable and then used by Main() when displaying the result.

The division is carried out, and the return value usually shows the result.
With this, we already have a complete program.
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Here starts the application
static void Main(string[] args)
{
// Required variables
int option = 0;
string value = "";
// We show the menu
Console.WriteLine("1-Sum");
Console.WriteLine("2-Subtraction");
Console.WriteLine("3-Multiplication");
Console.WriteLine("4-Division");
// We ask for the option
Console.WriteLine("What is your option:");
value = Console.ReadLine();
option = Convert.ToInt32(value);
// We check for the sum
if (option == 1)
{
Sum();
}
// We check for the subtraction
if (option == 2)
{
// Variable for our result
float result = 0;
// We invoke and obtain the result
result = Subtraction();
// We show the result
Console.WriteLine("The result of the subtraction is {0} ", result) ;
}
// We check for multiplication
if (option == 3)
{
// Required variables
float n1 = 0;
float n2 = 0;
string number = "";
// We ask for the values
Console.WriteLine("Give me the first number");
number = Console.ReadLine();
n1 = Convert.ToSingle(number);
Console.WriteLine("Give me the second number");
number = Console.ReadLine();
n2 = Convert.ToSingle(number);
// We invoke the function
Multiplication(n1, n2);
}
// We check for division
if (option == 4)
{
// Required variables
float n1 = 0.0f;
float n2 = 0.0f;
float result = 0.0f;
string number = "";
// We ask for the values
Console.WriteLine("Give me the first number");
number = Console.ReadLine();
n1 = Convert.ToSingle(number);
Console.WriteLine("Give me the second number");
number = Console.ReadLine();
n2 = Convert.ToSingle(number);
// We invoke the functio n
result = Division(n1, n2);
// We show the result
Console.WriteLine("The result is {0}", result);
}
} // Main closure
static void Sum()
{
// Required variables
float a = 0;
float b = 0;
float r = 0;
string number = "";
// We ask for the values
Console.WriteLine("Give me the first number");
number = Console.ReadLine();
a = Convert.ToSingle(number);
Console.WriteLine("Give me the second number");
number = Console.ReadLine();
b = Convert.ToSingle(number);
// We calculate the result
r = a + b;
// We show the result
Console.WriteLine("The result is {0}", r);
}
static float Subtraction()
{
// Required variables
float a = 0;
float b = 0;
float r = 0;
string number = "";
// We ask for the values
Console.WriteLine("Give me the first number");
number = Console.ReadLine() ;
a = Convert.ToSingle(number);
Console.WriteLine("Give me the second number");
number = Console.ReadLine();
b = Convert.ToSingle(number);
// We calculate the result
r = a - b;
// We return the result
return r;
}
static void Multiplication(float a, float b)
{
// Required variables
float r = 0;
// We calculate the value
r = a * b;
// We show the result
Console.WriteLine("The result is {0}", r);
}
static float Division(float a, float b)
{
// Required variables
float r = 0;
// We check for division by zero
if (b == 0)
{
Console.WriteLine("Cannot divide by zero");
return 0.0f;
}
else
{
r = a / b;
return r;
}
}
}
}

Optimizing the Functions


We already know how to use the different types of functions, and now we will learn how we can
optimize a program using them. In the previous program, we can think that we have used all the
necessary functions. But we know that a good opportunity to make use of the functions is when
we have constantly repeating code. If we look at our program, we can see that this happens.
In our program, we have something that happens eight times. The values are requested to be used
by the user at various places in the program. Every time we ask for it, we use three lines of code,
and the way it is requested is very similar between them.
When we have these cases, we have to carry out a little analysis. The first thing we ask ourselves
is: what function does this code perform? The answer is to ask for a floating value. Then we have
to ask ourselves if the function needs any data or data to be able to work.
At first glance, it seems not, since the user is the one who is going to enter the data. However, if
we look deeply, we will see that we really do need a piece of information. The request is carried
out through a message, and this message may be different in each case. We can have as data the
message to be displayed by the user. This will enter as a parameter in our function. The last
question to ask is: does the function need to return something? In this case, it is very easy to
deduce that yes. What we need to return is the value that the user has given us.
Already with this information, we can build our function. If the function were more complicated,
we would need to make the corresponding flow diagram. Fortunately, our function is very simple
and it is as follows:
static float FloatingRequest (message string)
{
// Required variables
float number = 0.0f;
string value = ””;
// We show the message
Console.WriteLine (message);
// We get the value
value = Console.ReadLine ();
number = Convert.ToSingle (value);
// We return the data
return number;
}
Let's start to see how this function we have created works.
The name is FloatingRequest since, as we know, the name of the function has to indicate a
reference to the type of work it performs. Since our function returns a float type value, then we
put float as its type.
The function has a single parameter, which is the message that we want to show the user in the
request. Since it is a text message, then the type that is most convenient to use is a string. We
name our parameter message.
Inside the function, we declare two variables. One is the number that we are going to receive
from the user, and the other variable is the string that we use with ReadLine (). Then we show
the request message. In the usual way, we obtain the value given by the user. To finish, we
simply return the number. To invoke this function, we will do it as follows:
n1 = FloatingRequest ("Give me the first number");
Now we see that instead of using the three lines of code per request, we simply invoke our
function. But this is not the only change we have to make. In the original program, we had
placed working variables to support the value request, but they are no longer necessary.
If we change the program to make use of our new function, it will look like the example below:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Here starts the application
static void Main(string[] args)
{
// Required variables
int option = 0;
string value = "";
// We show the menu
Console.WriteLine("1-Sum");
Console.WriteLine("2-Subtraction");
Console.WriteLine("3-Multiplication");
Console.WriteLine("4-Division");
// We ask for the option
Console.WriteLine("What is your option:");
value = Console.ReadLine();
option = Convert.ToInt32(value);
// We check for the sum
if (option == 1)
{
Sum();
}
// We check for the subtractio n
if (option == 2)
{
// Variable for our result
float result = 0;
// We invoke and obtain the result
result = Subtraction();
// We show the result
Console.WriteLine("The result of the subtraction is {0}", result);
}
// We check for multiplication
if (option == 3)
{
// Required variables
float n1 = 0;
float n2 = 0;
// We ask for the values
n1 = FloatRequest("Give me the first number");
n2 = FloatRequest("Give me the second number");
// We invoke the function
Multiplication(n1, n2);
}
// We check for division
if (option == 4)
{
// Required variables
float n1 = 0.0f;
float n2 = 0.0f;
float result = 0.0f;
// We ask for the values
n1 = FloatRequest("Give me the first number");
n2 = FloatRequest("Give me the second number");
// We invoke the function
result = Division(n1, n2) ;
// We show the result
Console.WriteLine("The result is {0}",
result);
}
} // Main closure
private static float FloatRequest(string v)
{
throw new NotImplementedException();
}
static void Sum()
{
// Required variables
float a = 0;
float b = 0;
float r = 0;
// We ask for the values
a = FloatRequest("Give me the first number");
b = FloatRequest("Give me the second number");
// We calculate the result
r = a + b;
// We show the result
Console.WriteLine("The result is {0}", r);
}
static float Subtraction()
{
// Required variables
float a = 0;
float b = 0;
float r = 0;
// We ask for the values
a = FloatRequest("Give me the first number");
b = FloatRequest("Give me the second number");
// We calculate the result
r=a-b;
// We return the result
return r;
}
private static float FloatingRequest(string v)
{
throw new NotImplementedException();
}
static void Multiplication(float a, float b)
{
// Required variables
float r = 0;
// We calculate the value
r = a * b;
// We show the result
Console.WriteLine("The result is {0}", r);
}
static float Division(float a, float b)
{
// Required variables
float r = 0;
// We check for division by zero
if (b == 0)
{
Console.WriteLine("Cannot divide by zero");
return 0.0f;
}
else
{
r = a / b;
return r;
}
}
static float request(string message)
{
// Required variables
float number = 0.0f;
string value = "";
// We show the message
Console.WriteLine(message);
// We get the value
value = Console.ReadLine();
number = Convert.ToSingle(value);
// We return the data
return number;
}
}
}
If we look at the code, we can see that it is easier to read and looks more organized. We have
also reduced the places where we can have a no-taxi or logic error. Now run the program to
check if it works correctly. You can select any operation from available list.
Another point to keep in mind is that the functions are invoking our function without any
problem. Remember that functions can invoke functions.

Pass By Copy and Pass By Reference


We have to learn an important concept about parameters and functions. The best way to do this is
through a simple experiment. We have previously discussed two concepts. The first is that
variables have a scope, that is, the parts of the program where they can be used depending on
where they were declared. The other concept is that when we invoke a function and pass
parameters, a copy of the parameter value is passed to the function. Let's start with our
experiment. We are going to create a program with the following code.
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Here starts the application
static void Main(string[] args)
{
// Required variables
int number = 5;
// Value before function
Console.WriteLine("Value before function {0}", number);
// We invoke function
Change(number);
// Value after function
Console.WriteLine("Value after function {0}", number);
}
static void Change(int number)
{
// We change the value
number = 17;
}
}
}
In the program, we have two functions, the Main () function and the Change () function. In Main
(), we are declaring a variable and assigning it the value of 5. Then we print a message that
shows the value of our variable before invoking the function. Immediately we invoke the
function, and after this, we print another message that shows us the value of the variable.
We do this to verify if the variable is affected by the function. The function is very simple; it
simply receives a parameter and assigns it a new value. This program might look like it would
present a different value before and after the function, but let's run it and see what happens.

The value of the variable is the same before and after the execution of the function.
When executing, we notice that the value of the variable is the same before and after invoking
the function. In other words, the function did not alter the value of the variable, although it
seemed that it would. Let's see the reason for this.
The first reason why this happens is that the variable was declared in the Main () function, that
is, only this function knows it and can use it directly. Main () is the scope of the variable. Then
we have that when the parameter is passed in this way, it is not actually the variable that is being
passed, but a copy of its value. So when our function tries to change the value, it changes to the
copy and not to the original variable.
When we pass the parameters in this way, we say that they go through a copy. But there is
another way to pass the parameters, and it is known as step by reference. Let's change our
program so that it is as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Here starts the application
static void Main(string[] args)
{
// Required variables
int number = 5;
// Value before function
Console.WriteLine("Value before function {0}",
number);
// We invoke function
Change(ref number);
// Value after function
Console.WriteLine("Value after function {0}",
number);
}
static void Change(ref int number)
{
// We change the value
number = 17;
}
}
}
Let's run the program first and then see what happens.
In this case, the value of the If variable changed; this is because the reference to the variable was
passed.
In this case, we are passing the parameter by reference. When this happens, instead of passing a
copy of the value, what we pass is a reference to where the variable is in memory. In this way,
any assignment to the variable is made on the original variable, and its value can be changed
even though it has been defined elsewhere.
To indicate that a parameter needs to be passed by reference, it is necessary to use the ref
statement, both in the invocation of the function and in its declaration. We can have more than
one variable passed by reference in a function.
Passing by reference is very useful, especially for cases when a function must return more than
one value. As we know, the return can only return one value. But by using references, we can
have a function that returns more than one value by modifying the passed variables.
Let's look at an example of this. We are going to create a function that allows exchanging the
values of two variables. This problem may seem simple, but without the use of references, it is
impossible to solve it with a single function. Next, we will see how our program is.
using System;
using System.Collections.Generic;
using System.Text;
namespace BaseApplication
{
class Program
{
// This is the main function of the program
// Here starts the application
static void Main(string[] args)
{
// Required variables
int a = 5;
int b = 3;
// Value before function
Console.WriteLine("Values before function a = {0}, b = {1}", a, b);
// We invoke function
Change(ref a, ref b);
// Value after function
Console.WriteLine("Values after function a = {0}, b = {1}", a, b);
}
static void Change(ref int x, ref int y)
{
// working variable
int temp = 0;
// We change the value
temp = x;
x = y;
y = temp;
}
}
}
If we run it, we get the following:
The values have been exchanged for the function.
As we can see, we make use of a working variable to help us in the interchange of values. The
step by reference allows us to modify both variables.

Use of Default Parameters


One of the new features that we found in the latest version of C # is the use of default parameters
in functions. With the functions we have been using, it is necessary to provide the function with
all the parameters with which it was declared. In other words, if the function has two parameters,
when we invoke it, we must give it two values so that it works with it.
With the default parameters, it is possible to place a default value on the parameter, so that if the
value is not explicitly given in the function invocation, then the default value is used. This can be
useful when we have parameters that, in the vast majority of cases, use the same value. In this
way, when we invoke the function, we do it using only the values that change, which allows us
to write less. Only when necessary, we put the value in the parameter.
We can see this in the following example, which has a function with default parameters and is
invoked traditionally and then using the default parameter. When you make use of the default
parameter imposed, it uses the value of 0.16.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cap5_5
{
class Program
{
static void Main(string[] args)
{
double cost = 50.0;
double tax = 0.0;
double total = 0.0;
// We use the function in a traditional way
tax = CalculateTax(cost, 0.25);
total = cost + tax ;
// We print result
Console.WriteLine("Total is $ {0}", total);
// We make use of the function with default parameter
// Note that we only pass one parameter, the other uses
// the default
tax = CalculateTax(cost);
total = cost + tax;
// We print result
Console.WriteLine("Total is $ {0}", total);
}
public static double CalculateTax(double quantity,
double tax = 0.16f)
{
double taxCalculated;
taxCalculated = quantity * tax;
return taxCalculated;
}
}
}
With this, we have seen the fundamental principles and uses of functions. The functions are very
useful, and we will continue to use them frequently through the next books of the series of C#.

Some Important Notes


The Name of the Function
It is important to select the name of the function correctly. The name should refer to the type of
work that the function performs; in many cases, we can make use of verbs. The variable name
can have numbers, but it must start with a letter.
Problems in Declaring Functions
Functions cannot be declared inside another function. This leads us to a syntax and logic error
that must be corrected as soon as possible. It is important to keep the functions in order and be
careful not to unbalance the {} when creating new functions. Remember that they must go inside
a class.
Name in Invocation
A very common mistake when starting to program functions is making a mistake when writing
the function name differently during invocation. For example, if our function is declared as Sum
() when we invoke it, we cannot use sum (). The invocation must use the function name exactly
as it was declared.
Be Careful With the Type of Return
The variable that receives the return value of the function must have the same type as the
function. If not, we can have from compilation problems to loss of precision in numerical values.
In some cases, if the types are different, it will be necessary to carry out conversions between the
types.
Return’s Position in the Function
It is not strictly necessary that the return is placed at the end of the function, although generally,
we will find it there. It is also possible to have several returns written, for example, one in each
case of an if ladder. What we must not forget is that when the execution finds the return, the
function ends.
Parameter Order
During the function invocation, the parameters must be placed in the same order in which they
were declared. Failure to do so can lead to parameters receiving wrong data. This is one of the
points that we must take care of. It is also good to name the parameters in such a way that their
names remind us of the information that will be placed on them.
Types of Parameters
The data we send must be compatible with the types that the function expects to receive as
parameters and, if possible, of the same type. We can make use of conversions before sending
the data to the function. With non-compatible data, we will have compilation problems in
compatible data, but not of the same type, and we will have a loss of precision problems.
To Know the Functions
The .NET development environment allows us to see the functions or methods that a particular
class has. When you write the name of the object of the said class followed by the dot operator, a
list of them appears. We can do this with the Console class. Investigating these functions allows
us to learn more about .NET and what we can do with it.
The functions allow us to have specialized sections of code in our application, reduce the amount
of code needed, and reuse the code efficiently. The functions consist of five parts, and there are
four types of them. The function can receive information through the parameters and return
information through the return. It is possible to pass the parameters by copy or by reference.
Conclusion

A few years ago, programming for Windows was complicated and required a high degree of
specialization. The .NET Framework solves many of the problems related to Windows
programming and interoperability. .NET applications are compiled to an assembly that contains
the program written in CIL.
This is an intermediate language that the runtime reads when the application is run. The CLR
compiles the CIL for the microprocessor as needed; the use of a runtime gives .NET the
flexibility of being cross-platform. All .NET languages must comply with the guidelines found in
the CLS.
The most important point about C #: it is a modern programming language. It simplifies and
modernizes C ++ in the areas of classes, namespaces, method overloading, and exception
handling. The screen abandons the complexity of C ++, making it easier to use and less error-
prone.
Contributing to C # 's ease of use is the reduction of some C ++ features, and no longer macros,
templates, and multiple inheritances. Especially for enterprise developers, the above features will
only produce more trouble than benefits. New features that make programming easier are strict
type safety, version control, garbage collect, and more. The goal of all these functions is to
develop component-oriented software.
Your effort to learn C # is a big investment because C # is designed for the primary language of
writing NGWS applications. You will find a lot of functions that you can achieve or laboriously
implement in C ++, which are just some basic functions in C #. For enterprise-level
programming languages, new financial data types are popular. You use a new decimal data type
that is dedicated to financial calculations. If you don't like this simple ready-made type, you can
easily create a new data type based on the special needs of your application.
Wouldn't you expect a new language not to support object-oriented features? C # certainly
supports all key object-oriented concepts, such as encapsulation, inheritance, and polymorphism.
The complete C # class pattern is built on top of the Virtual Object System (VOS) of the NGWS
runtime. VOS will be described in the next chapter. The object pattern is only part of the
foundation and is no longer part of the programming language.
The first thing you must focus on is that there are no more global functions, variables, or
constants. Everything is encapsulated in the class, including case members (through the class's
case-objects are accessible) or static members (through data types). These make C # code more
readable and help reduce potential naming conflicts.
The C # language evolved from C and C ++. It was created for enterprise developers who are
willing to sacrifice a bit of low-level features of C ++ to get more convenient and productive. C #
is modern, simple, object-oriented, and type-safe. Although it borrows a lot from C and C ++,
there are still huge differences between specific areas such as namespaces, classes, methods, and
exception handling.
C # provides you with convenient functions such as garbage collection, type safety, version
control, and so on. The only "cost" is that code operations are type-safe by default, and pointers
are not allowed. It's all about type safety. However, if you need pointers, you can still use them
with non-secure codes, and you cannot have column sets when calling non-secure codes.
Resources

https://docs.microsoft.com/en-us/dotnet/csharp/getting-started/
https://docs.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-aspnet-core
https://dotnet.microsoft.com/learn/dotnet/in-browser-tutorial/1
https://csharp.net-tutorials.com/
https://www.homeandlearn.co.uk/csharp/csharp.html
https://study.com/academy/lesson/5-basic-elements-of-programming.html
http://www.cs.fsu.edu/~cop3014p/lectures/ch2/index.html
http://ineasysteps.com/essential-elements-program/
https://overiq.com/c-programming-101/basic-elements-of-a-c-program/
https://theory.uwinnipeg.ca/programming/node3.html
https://www.studytonight.com/c/decision-making-in-c.php
https://www.w3schools.in/c-tutorial/decision-making/
https://www.programiz.com/c-programming/c-decision-making-loops-examples
https://www.techbeamers.com/c-decision-making/
https://www.tutorialspoint.com/cprogramming/c_for_loop.htm
https://www.programiz.com/c-programming/c-for-loop
https://beginnersbook.com/2014/01/c-for-loop/
https://intellipaat.com/blog/tutorial/c-tutorial/c-loops/
https://www.tutorialcup.com/cprogramming/decision-making-and-loops.htm
https://beginnersbook.com/2014/01/c-functions-examples/
https://www.geeksforgeeks.org/functions-in-c/
https://www.programiz.com/c-programming/c-functions
https://www.tutorialgateway.org/types-of-functions-in-c/
https://www.csharpstar.com/c-program-to-perform-all-basic-arithmetic-operations/
https://www.sanfoundry.com/csharp-programs-perform-arithmetic-operations/
C#
Simple and Effective Tips and Tricks to Learn C#
Programming Effectively

BENJAMIN SMITH
Introduction

This book contains proven steps and strategies on how to program in C# or C Sharp. This book
will help you learn the basics of C# programming simply and effectively. I have written and
tested all the code samples that I have included in the book. You have the permission to copy the
code and paste in the editor or compiler to see the results. I recommend that in the first attempt
you should copy and paste the code to have a feel of how you a program in C# looks like. When
you think that you have acquired sufficient knowledge and have also refurbished your
programming skills, you can edit the sample codes by changing variable names, class names,
values of the integers, and add more class instances. Afterward, you can compile the code and
see the results.
You should not worry if you don’t see the desired results and see an error message instead. I
have dedicated a comprehensive section on what possible errors you may come across during the
programming phase and what the error message will look like. All you need is to study the error
message and understand its context. Then you can easily remove the errors and streamline the
code. When you have gained expertise in reading and understanding the error messages, you will
make fewer errors.
C# programming language is a powerful language. It is relatively mature and is a descendant of
C and C++. It also retains certain features of the Java language. Programming with C# is great
fun. Microsoft created C# as a part of the .NET initiative. This book will explain the ins and outs
of C# programming language. You will learn how to write usable programs. For which purpose,
you will need a particular coding environment. We bet that most of the readers will definitely use
Microsoft Visual Studio. There are alternatives that you can lay your hands on.
I learned to program when I was in high school. I didn’t study programming in the school or
college. Instead, I learned it by reading a bunch of good books and practice. My love for coding
started with an incident. I used to study history at school. Like all the other teenagers, I was in
love with my computer and the internet. One day I was coming back from school to home. It was
a dull afternoon. The sky had gone behind thick clouds when I put my car on the highway. It was
a beautiful sight and scary too. The line of trees along the edge of the road had starts swaying
back and forth being pushed by gusts of wind. I knew a storm was likely to hit the town. And it
did. It went dark suddenly. I was afraid, to say the least. It rained heavily that afternoon. The
wind smashed the car windows but I kept driving until I got out of the storm. I reached home by
evening only to find that my system applications had been shattered in a hacking attack. I used to
run an online application that I had got developed by a friend. I wondered if he would develop
the same from scratch again. He refused to cite the reason that he had been busy in research
work. I was disappointed, to say the least. He ruined my life.
That day I decided to take over the control of developing my applications. I learned C# along
with other programming languages and I found it the best out of all of them. My craze for coding
didn’t stop there but it increased several folds. I built one after another application and also sold
some to fellow students.

What This Book Has for You


This book is the best for those who want to learn C# programming from scratch. Every beginner
should read this book. You don’t have to be an expert programmer to benefit from the
knowledge in this book. This book is divided into chapters that deal with different topics. The
book contains code samples for each feature of C# I explain. To make the samples easier to
understand, I must say that I have written them in an editor. The editor usually has two parts; one
part pertains to the written code space where you write. The other part pertains to space where
you can see the compiled results. I have shown the two spaces with a single line between the two
so that you may understand the program in a better way. This is how you can match your results
with mine. If there is a difference, you can double-check the written code and match it with mine
to see where you have missed. Sometimes, programmers misspell a word at two different spots.
At other times, programmers fail to keep up the cases of the words in check. They use uppercase
for the first letter at one point and use lowercase for the same letter at another point. This can
make practicing a frustrating job. However, if you do it carefully and wisely, you can keep these
errors in check.
The first chapter will explain to you what C# is. You will learn about the working of a visual
studio. Visual studio is a compiler in which you can write your code and compile a program. I
will explain in this section how you can download visual studio and install it on your system.
You will also learn how you can use it to write and compile C# programs. The next section of the
book is about creating the console program. The chapter ends with saving the code.
The second chapter of the book deals with getting started with C# programming. You will learn
about writing C# strings. If you are acquainted with programming languages, you might know
what strings are and how you can use them while writing a program. A string is a data type that
can store a piece of text. You can fill it in a thousand pages of text if your program demands it.
The text which is stored in a string is generally stored as a collection of Char objects. String
objects are immutable and you cannot change them after you have created them. All the string
methods and operators that seem like modifying a string tend to return the results as a new string
object. You can create as many strings for your program as you need. It will not overfill the
program. After defining the string, the chapter will move on to explaining the comparison of
strings. The next section of the chapter will shed light on the length of strings and string methods
as well. You can concatenate strings which, in simple language, means that you can add together
two strings. You will have to use a new variable to transfer the results of the addition of the
strings.
The chapter further moves on to explain C# arrays and lists. You will learn how you can create
an array in C#. I will explain with an easy-t0-digest example. You will get the opportunity to
create an array by adding different objects to the array. You can create an array first and then
keep adding different objects to the same along the way. The next section of the chapter will
explain how you can know what the length of an array is. The chapter then glides down to
explain how you loop through an array. Once you have created an array, you can remove its
items by a simple method. I will explain how to do that. This can be useful if you are creating a
game in which a character sells fruits.
When the fruit is sold out, the player can have the opportunity to remove them one by one. The
last section of this chapter explains lists. I will start by getting you acquainted with different
methods of creation of lists. You can create a list that contains numbers and you also can create a
list that contains pieces of texts such as names of vegetables and fruits. Once you have
familiarized yourself with how you create lists, you can move on to learning how to remove
items from a list. There are two methods to do that. One method relates to directly removing
items by using names. The other method is by removing items by using the index number. Fill in
the list methods with an index number and afterward let C# count the remaining items. You will
get the total number minus the removed item. There is a dedicated method for concatenation in
C# programming language which I will explain at the end of the chapter.
The third chapter of the book revolves around conditionals. Conditional statements are the keys
to testing certain conditions, perform mathematical functions, and display interactive messages to
users when they use your program. The first in the line is the if statement. I will explain by code
samples how you can create an if statement and for which purpose you can use them while
building a program. The next section of the chapter deals with the else statement which is a step
further to the if statement. If one statement stands false, the else statement is put to work. It takes
the rest of the code to a conclusion. The third section deals with the else-if statement. It forms the
third block of code in the construction of the conditionals. Now there are three conditions at
work. I will explain how you can use three conditionals to test different conditions and build
complex programs. The chapter ends on explaining the shorthand else-if statement. These
statements are recommended only for seasoned programmers who can easily understand written
code even if it is written on the same line. Otherwise, the lengthy method is the best to choose
and try.
The fourth chapter of the book is about interactive programming using C#. The first section of
the book focuses on user input. You can invite the users to fill your program with the type of
information that you need from them. The second section specifies the type of input that you
want your users to add to the program. The third section of the book focuses on the switch
statement and the usage of the break keyword.
The fifth section of the book deals with C# loops. You will learn what a while loop is and how
you can create it in C#. The while loop in C# programming language is the same as in any other
programming language. You can write it and use it to create a program that repeats and tests the
condition as long as it stands true. It stops at the point the condition stands false. The next on the
line is nested while loop. You can nest it inside of the main while loop to create a combination in
which one while loop will test each navigation of the first loop. I have written a sample code that
you can paste in the compiler you are using and test what happens. The next section of the
chapter focuses on the do-while loop and a nested do-while loop. In this chapter, you will learn
what for loops are, how you can create them, and what purpose they are written for. You will get
to learn multiple expressions regarding the for a loop. You will also learn about what nested for
loops are. I will explain the significance of foreach loop to sort out arrays. The chapter has
something really interesting in common. If you know how to drive, you know how to put the
brakes on and push the paddle. Of course, you will have code samples to practice the break and
continue statements so that you can learn in a better way.
The sixth chapter of the book deals with methods. If you are aware of Python, you may know
that Python has functions that you can create and call later on. The best thing about Python
functions is that you can create them once and use them as many times as you need. They cut
down the coding time, and also save you from the hassle of writing the same code again and
again for different purposes. This is why functions are considered the lifeline of Python. As
Python has functions to offer, C# has methods. They do just the same thing that functions do.
You can create them once and use them at will. The first section of this chapter defines what
methods are. The second section of the chapter explains what parameters are, how you can create
them, and how you can pass them to the methods to create a program. You also can use multiple
parameters to pass on to C# methods. In the next section of this chapter, I will explain how you
can return values in a method. You can do calculations and store the result in a separate variable.
This is how methods work.
The seventh chapter of the book deals with object-oriented programming. The first section of the
chapter helps you create a C# class, the same as classes in Python or Java. They serve the
purpose of creating real-life models or objects. For example, I will create a Cat class or a Dog
class. I will then give them certain attributes that real cats and dogs possess. After educating on
how to create a C# class, I will explain how you can create a car class. This program can help
you if you run a car showroom. You can add instances in the car class whenever you receive a
new car for the showroom. The instance will act as a new object and will be stored in the
database of the program. This is how you can build a powerful program that can serve your
commercial needs. I will shed light on class members and class methods. The class constructor is
one of the most interesting topics in the book. It makes making classes easier for you. It guides
you and cuts down the steps for making classes. You can pass multiple parameters to a class, but
I will explain that by example. The chapter ends on explaining what C# properties are how you
can use them for your benefit.
The eight-chapter of the book carries an in-depth explanation of C# classes. You will learn in
this chapter a bunch of interesting concepts such as polymorphism, interfaces, and abstraction.
All these concepts belong to C# classes. At the end of the chapter, I will try to educate you on
different error messages. C# is a compiled language. Python developers can see through the error
easily as the editor or terminal mentions the line on which you have made the error. However,
C# doesn't offer such a privilege. Therefore, I have explained different types of error messages as
to how they look and what are the driving factors behind each error message. You can feed the
messages in mind to familiarize yourself with them so that you may be able to detect them and
fix them when you hit one
The ninth chapter is the last of the book. In this chapter, I will explain how to write secure code
and what types of attacks you may experience in your programs. The first topic of this chapter is
about building a secure design for your program. The next topic is about the documentation of
the threat like defining its nature, defining the scope of the attack, and analyzing the extent of the
damage the attack can inflict on your application. At the end of the chapter, I will give you a
brief glimpse of STRIDE which explains different types of attacks on applications.
In conclusion, I will explain how C# can benefit you and why you should immediately switch to
C# programming. You will have more than one reason to do that if you read it carefully.
Everyone who has the basic knowhow of programming can read this book. Even if you are a
novice in the world of programming, this book will walk you through the world of C# and help
you learn the basics. You can practice and reach the advanced programming level gradually. I
recommend that you grab a notebook, a pen, and a laptop when you start reading the book. It is a
technical book and you should read it like that. Once you read a brief for a C# feature and go
through the sample code, you should write it down or use it in a compiler for practice. The more
you practice each sample code by using it as it is and by editing the same by making small
changes to have a feeling that you are writing the code yourself. Make sure you keep track of the
changes or you will not be able to fix any errors that may pop up.
The book is an interesting read and by the time you have made it to the end, you will be
equipped with the basics and the advanced levels of C# programming. You will be able to write
real programs that are based on Object-Oriented Programming (OOP) which is the most popular
aspect of C# language.
Chapter One
What Is C#?

The C# programming language is one of the languages that programmers use to build executable
programs. C# is a powerful object-oriented language. It is open-source, modern, simple, and
flexible, and is also quite a versatile language. A programming language is something that you
can use to write software programs. C# is a simple language that also supports modern-day
functionality for different types of software development. C# was designed in the first place to
help enterprises and businesses. It caters to all of their needs. It was designed to build different
software for businesses. C# provides much-needed functionality to support modern-day software
development. It supports mobile and web app development.
C# is open source under .NET Foundation. Microsoft governs and runs the foundation. C#
language compilers, specifications, and tools can be found as open-source projects on GitHub.
C# is flexible as the programs built with it can be executed on the current machine or they can
simply be transmitted on the Web. You also can execute them on some distant computer. C# is
powerful because it has the same command set as that of C++. It error-proofs the commands that
are responsible for several C++ errors so that you spend less time chasing them down.
The .NET code library that C# uses for its capabilities offers the help that is needed to create
complicated display frames, including drop-down lists, grouped buttons, background images,
tabbed windows, and scroll bars. C# tends to play a pivotal role in the .NET Framework.

What Is Visual Studio?


Programmers label Visual Studio an Integrated Development Environment (IDE). This IDE aids
you in creating native code and managed code as well. Visual Studio was released in 1997 and
since then it has been considerably evolved. The latest version is known as Visual Studio 2017.
The details of the three versions of Microsoft Visual Studio are as follows.
Community
This is a free version. The features are much more the same as of the professional editions. You
can use this edition to develop an application such as web applications and .NET applications.
However, if you want it for an enterprise organization, you may have to face some limitations. If
your organization has revenue above $1 million a year, you cannot use this free version. You can
code in JavaScript, C#, Python, F#, HTML and Python by using this free version.
Professional Version
This is the commercial edition that offers support for XSLT and XML editing. You also can
integrate it with Microsoft SQL Server. You can download and install it for a free trial to get a
knowhow of its unique and additional features. You will get professional tools for developing
apps. Features like CodeLens tend to improve the productivity of your team.
Enterprise Version
This version is an end-t0-end solution for big teams that have unique quality demands. You can
get a 90-day free trial for this version. When the trial period ends, you can pay for it to continue
using it. One of the major benefits of this edition is that you can build high-quality software.
There is a code editor in each version where you will get to write the code. Paired up with that is
an output window where you can see the results of the code, error messages and warnings issued
by the compiler.
You can create or save a project using the File menu, while the Edit menu offers modification
and refactoring of different code commands. You can use the Project menu for adding different
dependencies to the project.

Creating the Console Application


Microsoft Visual Studio 2010 carries an Application Wizard that tends to build template
programs. It also saves you a lot of dirty work that you would have to do if you started from
scratch. Starter programs don’t do anything useful. However, they do get you beyond the initial
hurdle of starting the development phase. Some of the starter programs are sophisticated. A
console application is the one that runs in a console on your Windows. You can refer to it as the
command window or DOS prompt. If you hit Ctrl + R and after that type cmd, a window will
pop up on the screen. It is the console where your application will run.
To start Visual Studio, you need to choose to navigate to Start then All Programs then Microsoft
Visual Studio. You will have to create a console app at the start. Open Visual Studio 2010 and
hit the New Project icon. In the new window, select Visual C. You will be required to create a
project before you enter your C# program. A project is like a folder in which you need to throw
your files that make your program. You will get hold of a set of configuration files to aid the
compiler is doing its job. The default place to store your files is in the Documents directory.
The default place to store the file is in the Documents directory. You also can change the default
program location. Go to Choose Tools and click Options. You will see Choose Projects and
Solutions. Click on the General and select the new location. Click Ok.

Saving Code
When you have written code, you can save it in a handy location to use in the future. That
location is the Toolbox window. You have to follow these steps. In the Main() method of the
class Program, you need to select the lines you have to save. Open the Toolbox window. Open it
by choosing View and then click on Toolbox. Now drag the selected lines in the General tab onto
the Toolbox window and drop the same. You can, anytime, reuse the code in the future.
Chapter Two
Getting Started With C#

The most basic concept is of variables in all programming languages. A C# variable, like that of
other languages, is a small container that stores different things like numbers. The term variable
comes from mathematics. In C# there are several limitations for programmers when it comes to
using them to building programs. This chapter will walk you through the world of variables. You
will learn how to declare them, initialize them, and use them in C#.
You might have learned in the third grade the equation x = 1. By writing the equation, you are
declaring a variable. You are saying that the variable x has the value ‘1.’ In the world of
programming, you first have to define a variable in a specific way.
C# has different types of variables. The variable ‘int’ is used to store integers like whole
numbers without decimals. The variable ‘double’ is used to store floating-point numbers such as
20.67. The variable ‘char’ is used to store single characters such as ‘x’. You have to surround the
char values within single quotes. The variable ‘bool’ is used to store values with two states such
as false or true. The variable ‘string’ is used to store pieces of text; you will have to store string
values by double-quotes.
If you want to create a variable, you must specify its type and its value as well. Assign the
variable a name such as x and add an equal sign if you want to assign values to the variable. See
the following variable that should store text.
using System.IO;
using System;
class myProgram
{
static void Main(string[] args)
{
string sentence = "This is a C# program. I am creating a string by filling it in
with a particular value!";
Console.WriteLine(sentence);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
This is a C# program. I am creating a string by filling it in with a particular value!
In the following example, I will create a variable named thisNum in which I will store a number.
Take a look at the following example. I will create a variable named thisNum of int type. Will
also assign it a numeric value.
using System.IO;
using System;
class myProgram
{
static void Main(string[] args)
{
int thisNum = 22;
Console.WriteLine(thisNum);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
22
You also can create a variable first and assign the value later. See the following example.
using System.IO;
using System;
class myProgram
{
static void Main(string[] args)
{
int thisNum;
thisNum = 50;
Console.WriteLine(thisNum);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
50
If you have already assigned a value to a variable but you once again assign it in the next line,
the previous value will be overwritten by the latest value.
using System.IO;
using System;
class myProgram
{
static void Main(string[] args)
{
int thisNum = 25;
thisNum = 50;
Console.WriteLine(thisNum);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
50

C# Strings
A string is a class for which C# tends to offer special treatment because strings are widely used
in several programs. The keyword string is often confused with String. In the following example,
I will analyze different elements of a string.
using System.IO;
using System;
class myProgram
{
static void Main(string[] args)
{
String sentence = "This is a C# program. I am creating a string by filling it in
with a particular value!";
Console.WriteLine(sentence);
}
}
In this example, a sentence is an object of the class String. If we convert the uppercase of S into
lowercase, it will be a simple string. However, string or String is compatible with each other.
Once you have created a string object, you cannot change or modify it. C# lacks an operation
that tends to modify the string object. If you modify it, you will get a new object in return. That’s
how one string becomes two.
using System.IO;
using System;
namespace ModifyString
{
class Program
{
public static void Main(string[] args)
{
// I am now Create a brand student object.
newStudent s1 = new newStudent();
s1.Name = "Tom";
// Now I will make another new object that has the same name.
newStudent s2 = new newStudent();
s2.Name = s1.Name;
s2.Name = s1.Name.ToUpper();
Console.WriteLine("s1 - " + s1.Name + ", s2 - " + s2.Name);
Console.WriteLine("You are required to Press the Enter button to terminate...");
Console.Read();
}
}
class newStudent
{
public String Name;
}
}
$mcs *.cs -out:main.exe
$mono main.exe
s1 - Tom, s2 - TOM
You are required to Press the Enter button to terminate...
The ToUpper didn’t change the name. However, it created an independent uppercase string and
the stores the same in the new object s2. This property of strings is also known as the
immutability of unchangeability. It is important for string constants. As a C# programmer, you
will get to perform multiple operations on strings. Every program tends to use an additional
operator that you can use on strings. In the following example, I will use the + data operator to
concatenate different pieces into one.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string name = "Tom";
Console.WriteLine("I was pleased to meet him. His name was " + name + ".");
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
I was pleased to meet him. His name was Tom.

Comparison of Strings
It is quite common to compare two strings. If you want to know whether two strings are equal in
length or not, you can use the == operator to confirm. To see if they are unequal or not, you
should use the inverse operator !=.

String Length
A string in C# language is an object, which contains methods and properties that would perform
several operations on strings. For example, you can find the length of a string by using the
Length property.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence = "I am learning C Sharp. It is an interesting object-oriented
language.";
Console.WriteLine("The length of the above mentioned string is: " +
sentence.Length);
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
The length of the above mentioned string is: 68

String Methods
There are different string methods that you can use. To name a few, you can convert strings into
uppercase and lowercase by using some simple methods.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence = "I am learning C Sharp. It is an interesting object-oriented
language.";
Console.WriteLine(sentence.ToUpper());
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
I AM LEARNING C SHARP. IT IS AN INTERESTING OBJECT-ORIENTED LANGUAGE.
The above method converted the string to upper case. The following method will convert the
string into the lower case. See the example.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence = "I am learning C Sharp. It is an interesting object-oriented
language.";
Console.WriteLine(sentence.ToLower());
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
i am learning c sharp.it is an interesting object-oriented language.
There is a method to concatenate two strings. I will use the + operator to combine two strings
into a single whole. See the following example for details.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence1 = "I am learning C Sharp." ;
string sentence2 = "It is an interesting object-oriented language.";
string fullsen = sentence1 + sentence2;
Console.WriteLine(fullsen);
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
I am learning C Sharp. It is an interesting object-oriented language.
You can display the concatenated result in upper case as well by adding a simple method.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence1 = "I am learning C Sharp.";
string sentence2 = "It is an interesting object-oriented language.";
string fullsen = sentence1 + sentence2;
Console.WriteLine(fullsen.ToUpper());
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
I AM LEARNING C SHARP. IT IS AN INTERESTING OBJECT-ORIENTED LANGUAGE.
Now I will convert it into lowercase by adding the relevant method.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence1 = "I am learning C Sharp.";
string sentence2 = " It is an interesting object-oriented language.";
string fullsen = sentence1 + sentence2;
Console.WriteLine(fullsen.ToLower());
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
i am learning c sharp. it is an interesting object-oriented language.
String concatenation can also be done by using a dedicated concatenation method instead of the
+ operator. The method namely string.Concat() can be used to achieve the same goal.
using System.IO;
using System;
namespace MyApplication
{
class Progra m
{
static void Main(string[] args)
{
string sentence1 = "I am learning C Sharp.";
string sentence2 = " It is an interesting object-oriented language.";
string fullsen = string.Concat (sentence1, sentence2);
Console.WriteLine(fullsen.ToUpper());
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
I AM LEARNING C SHARP. IT IS AN INTERESTING OBJECT-ORIENTED LANGUAGE.
Another method for string concatenation is string interpolation, which substitutes the values of
different variables into placeholders in the string. You should note that you don’t have to worry
about the spaces as is the case with concatenation.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence1 = "I am learning C Sharp.";
string sentence2 = " It is an interesting object-oriented language.";
string fullsen = $"{sentence1} {sentence2}" ;
Console.WriteLine(fullsen.ToUpper());
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
I AM LEARNING C SHARP. IT IS AN INTERESTING OBJECT-ORIENTED LANGUAGE.
Access String
There is a method to access different characters in a string by referring to the index number
which is inside the square brackets.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence1 = "I am learning C Sharp.";
string sentence2 = " It is an interesting object-oriented language.";
Console.WriteLine(sentence1[9]);
}

}
}
$mcs *.cs -out:main.exe
Compilation succeeded - 1 warning(s)
main.cs(11,14): warning CS0219: The variable `sentence2' is assigned but its value is
never used
$mono main.exe
n
The compiler has issued a warning because I left the second string without assigning any method
to it. Let’s access a character in the second string.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence1 = "I am learning C Sharp.";
string sentence2 = " It is an interesting object-oriented language.";
Console.WriteLine(sentence1[10]);
Console.WriteLine(sentence2[15]);
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
i
e
There is a reverse method by which you can locate the index number of each character in a
string. All you have to do is to enter the alphabet of the string and C# will find the index number
linked to that alphabet. There is a specific method for the purpose, called the IndexOf() method. I
will use the same strings to test this method and see how effective it is when you are creating a
program.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence1 = "I am learning C Sharp.";
string sentence2 = " It is an interesting object-oriented language.";
Console.WriteLine(sentence1.IndexOf("S"));
Console.WriteLine(sentence2.IndexOf("t"));
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
16
2

Substrings
There is another useful method known as Substring() which extracts several characters from a
particular string. You can decide the specified character position and the method will come up
with a new substring. I will use this method in combination with IndexOf() to find out the
specific character position.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence2 = " It is an interesting object-oriented language.";
int charPos = sentence2.IndexOf("o");

string sentence3 = sentence2.Substring(charPos);

Console.WriteLine(sentence3);
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
object-oriented language.
In the next example, I will choose another point from where I will slice off the substring. I will
enter ‘i’ as the point from which the program should slice off the string and create a substring.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence2 = " It is an interesting object-oriented language." ;
int charPos = sentence2.IndexOf("i");

string sentence3 = sentence2.Substring(charPos);

Console.WriteLine(sentence3);
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
is an interesting object-oriented language.
The results were not as I had intended. I wanted to create the string starting from the word
‘interesting.’ However, the word ‘is’ also starts from the word ‘i’ and this came before the word
‘interesting’. As such the substring was created from the same word. There is a solution to this
problem. I will add another alphabet from the word interesting and expect the desired results.
Another alphabet from the desired word will add clarity to the program and the compiler will
find it easy to locate the desired word.
using System.IO;
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string sentence2 = " It is an interesting object-oriented language.";
int charPos = sentence2.IndexOf("in") ;

string sentence3 = sentence2.Substring(charPos);

Console.WriteLine(sentence3);
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
interesting object-oriented language.

C# Arrays & Lists


Arrays are created and used to storing multiple values in one variable instead of declaring
individual variables for each value. You will first have to declare an array and define the type of
variable that you will be filling in. When you have declared the variable, you need to place the
values in a comma-separated list within the curly braces.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
Console.WriteLine(fruits[0]);
Console.WriteLine(fruits[3]);
Console.WriteLine(fruits[1]);
Console.WriteLine(fruits[6]) ;
Console.WriteLine(fruits[8]);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
guava
banana
grapefruit
jackfruit
peach
Take another example in which I will try to access the items that are not in the index. You will
receive an error.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
Console.WriteLine(fruits[0]);
Console.WriteLine(fruits[3]);
Console.WriteLine(fruits[1]);
Console.WriteLine(fruits[6]);
Console.WriteLine(fruits[8]);
Console.WriteLine(fruits[7]);
Console.WriteLine(fruits[9]);
Console.WriteLine(fruits[2]);
Console.WriteLine(fruits[12]);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
guava
banana
grapefruit
jackfruit
peach
dragonfruit
apricot
apple
Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at MyApp.Program1.Main (System.String[] args) [0x0009a] in
<da27370ce8d24ef0a5fdcd220b94022f>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException:
Index was outside the bounds of the array.
at MyApp.Program1.Main (System.String[] args) [0x0009a] in
<da27370ce8d24ef0a5fdcd220b94022f>:0
You also can change an array element by referring to the index number of the element. See the
following example.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
fruits[0] = "plum";
Console.WriteLine(fruits[0]);
fruits[1] = "melon";
Console.WriteLine(fruits[1]);
fruits[2] = "watermelon";
Console.WriteLine(fruits[2]);
fruits[3] = "mango";
Console.WriteLine(fruits[3]);
fruits[4] = "lychee";
Console.WriteLine(fruits[4]);
fruits[5] = "tomato";
Console.WriteLine(fruits[5]);
fruits[6] = "orange";
Console.WriteLine(fruits[6]);
fruits[7] = "fig";
Console.WriteLine(fruits[7]);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
plum
melon
watermelon
mango
lychee
tomato
orange
fig

Array Length
You can check the length of the array by using the following code. Let’s try it.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
Console.WriteLine(fruits.Length);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
10

Array Loop
C# gives you the option of looping through the array elements with a for loop. You also can use
the Length property for specifying how many times the loop should run. The following example
will loop through all elements of fruits array.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
for (int i = 0; i < fruits.Length; i++)
{
Console.WriteLine(fruits[i]);
}
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
guava
grapefruit
apple
banana
strawberry
blueberry
jackfruit
dragonfruit
peach
apricot
If you change the symbol of less than to greater than, you will not have any results.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
for (int i = 50; i > fruits.Length; i++)
{
Console.WriteLine(fruits[i]);
}
}
}
}
The result will be an empty page. You also can change the value of i and the looping will be
limited. This can be handy in case you create a program for which you want the users to see only
a few elements.
using System;
using System.Collections.Generic;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
List<string> fruits = new List<string>();
// add fruits
fruits.Add(" apple ");
fruits.Add(" banana ");
fruits.Add(" orange ");
fruits.Add(" plum ");
fruits.Add(" guava ");
fruits.Add(" melon ");
fruits.Add(" watermelon ");
fruits.Add(" strawberry ");
fruits.Add(" blueberry ");
fruits.Add(" jackfruit ");
fruits.Add(" dragonfruit ");
// now remove the banana
fruits.Remove("banana");
Console.WriteLine(fruits.Count) ;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
11
Item Removal
If you want to remove items from a list, you can use another method for the purpose. If you are
creating a program in which a vendor sells fruit, you can write in such a way that whenever the
vendor sells out a particular fruit, the player will be able to remove the empty cart from the shop
by using the index number of the fruit.
using System;
using System.Collections.Generic;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
List<string> fruits = new List<string>();
fruits.Add(" apple ");
fruits.Add(" banana ");
fruits.Add(" orange ");
fruits.Add(" plum ");
fruits.Add(" guava ");
fruits.Add(" melon ");
fruits.Add(" watermelon ");
fruits.Add(" strawberry ");
fruits.Add(" blueberry ");
fruits.Add(" jackfruit ");
fruits.Add(" dragonfruit ");
fruits.RemoveAt(1);
fruits.RemoveAt(5);
Console.WriteLine(fruits.Count);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
9

C# Lists
C# has been fun to code in and one reason behind this is lists. This post will tell you how you can
fill items into a list. You can add, sort or remove different items from a list. C# has indexed lists
and like the arrays the index starts at 0. The items are not sorted. While an array has a fixed size,
the items in a list can be changed at will, which is why a list is the perfect choice if you don’t
know the number of items that you must include in it. It is estimated that you can pack up about
two million elements in a list if you are operating a 64-bit operating system.
using System;
using System.Collections.Generic;

class Program1 {

// Main Method
public static void Main(String[] args)
{

// I am now creating a List of integers


List<int> flist = new List<int>() ;

// I am here displaying the number


// of different elements of the List<T>
Console.WriteLine(flist.Count);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
0
See another example of C# lists. I will use more digits.
using System;
using System.Collections.Generic;

class Program1 {
// Main Method
public static void Main(String[] args)
{

// I am Creating the List of integers


List<int> flist = new List<int>();

// I am now adding the elements in flist


flist.Add(1);
flist.Add(2);
flist.Add(3);
flist.Add(4);

Console.WriteLine("The Capacity here Is: " + flist.Capacity);

Console.WriteLine("The Count here is: " + flist.Count) ;

flist.Add(5);
flist.Add(6);

Console.WriteLine("The Capacity here Is: " + flist.Capacity);

Console.WriteLine("The Count here Is: " + flist.Count);


}
}
$mcs *.cs -out:main.exe
$mono main.exe
The Capacity here Is: 4
The Count here is: 4
The Capacity here Is: 8
The Count here Is: 6
You can check in a list whether a digit is present or not by adding simple method to the code.
using System;
using System.Collections.Generic;

class Program1 {

// Main Method
public static void Main(String[] args)
{

// I am Creating the List of integers


List<int> flist = new List<int>();

// I am now adding the elements in flist


flist.Add(1) ;
flist.Add(2);
flist.Add(3);
flist.Add(4);
flist.Add(5);
flist.Add(6);

Console.WriteLine(flist.Contains(5));

}
}
$mcs *.cs -out:main.exe
$mono main.exe
True
If the digit is not present, the result will be different.
using System;
using System.Collections.Generic;

class Program1 {

// Main Method
public static void Main(String[] args)
{

// I am Creating the List of integers


List<int> flist = new List<int>();

// I am now adding the elements in flist


flist.Add(1) ;
flist.Add(2) ;
flist.Add(3) ;
flist.Add(4) ;
flist.Add(5) ;
flist.Add(6) ;

Console.WriteLine(flist.Contains(50));

}
}
$mcs *.cs -out:main.exe
$mono main.exe
False
Here is another example of list creation by using C#.
using System;
using System.Collections.Generic;

class Program1 {

// This is the Main Method


public static void Main(String[] args)
{

// Mow I am Creating a List<T> of Integers


List<int> flist = new List<int>();

// Adding elements to List


flist.Add(17);
flist.Add(19);
flist.Add(21);
flist.Add(9);
flist.Add(75) ;
flist.Add(19);
flist.Add(73);

Console.WriteLine("Take a look the elements present in the List:\n");

int p = 0;

// Now I am displaying elements


foreach(int k in flist)
{
Console.Write("We are at Position {0}: ", p);
Console.WriteLine(k);
p++;
}

Console.WriteLine(" ");

Console.WriteLine("I am removing the element at the index 3\n");

flist.RemoveAt(3);

int p1 = 0;

foreach(int n in flist)
{
Console.Write("now I am at Position {0}: ", p1);
Console.WriteLine(n) ;
p1++;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Take a look the elements present in the List:
We are at Position 0: 17
We are at Position 1: 19
We are at Position 2: 21
We are at Position 3: 9
We are at Position 4: 75
We are at Position 5: 19
We are at Position 6: 73
I am removing the element at the index 3
At Position 0: 17
At Position 1: 19
At Position 2: 21
At Position 3: 75
At Position 4: 19
At Position 5: 73
List Creation
You can create a list of fruits and count the numbers by using the following method. See the
example below.
using System;
using System.Collections.Generic;

class Program1 {

// This is the Main Method


public static void Main(String[] args )
{

List<string> fruit = new List<string>();


// add fruits
fruit.Add("Apple") ;
fruit.Add("Banana") ;
fruit.Add("Orange") ;
fruit.Add("Peach") ;
fruit.Add("Guava") ;
fruit.Add("Melon") ;
fruit.Add("Watermelon") ;
fruit.Add("Lychee") ;
fruit.Add("Strawberry") ;
fruit.Add("Blueberry") ;
fruit.Add("Raspberry") ;
fruit.Add("Dragonfruit") ;
fruit.Add("Jackfruit") ;
fruit.Add("Coconut") ;
fruit.Add("Banana") ;
// now remove the banana
Console.WriteLine(fruit.Count);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
15
Item Removal
If you intend to remove items from the list, there is a simple method to do that. See the following
example.
using System;
using System.Collections.Generic;
class Program1 {

// This is the Main Method


public static void Main(String[] args)
{
List<string> fruit = new List<string>();
// add fruits
fruit.Add("Apple") ;
fruit.Add("Banana") ;
fruit.Add("Orange") ;
fruit.Add("Peach") ;
fruit.Add("Guava") ;
fruit.Add("Melon") ;
fruit.Add("Watermelon") ;
fruit.Add("Lychee") ;
fruit.Add("Strawberry") ;
fruit.Add("Blueberry") ;
fruit.Add("Raspberry") ;
fruit.Add("Dragonfruit") ;
fruit.Add("Jackfruit") ;
fruit.Add("Coconut") ;
fruit.Add("Banana") ;
// now remove the banana
fruit.Remove("Banana");
Console.WriteLine(fruit.Count);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
14
You can remove the items by using the index number. The method for the purpose is called
RemoveAt().
using System;
using System.Collections.Generic;

class Program1 {

// This is the Main Method


public static void Main(String[] args)
{

List<string> fruit = new List<string>();


// add fruits
fruit.Add("Apple") ;
fruit.Add("Banana") ;
fruit.Add("Orange") ;
fruit.Add("Peach") ;
fruit.Add("Guava") ;
fruit.Add("Melon") ;
fruit.Add("Watermelon") ;
fruit.Add("Lychee") ;
fruit.Add("Strawberry") ;
fruit.Add("Blueberry") ;
fruit.Add("Raspberry") ;
fruit.Add("Dragonfruit") ;
fruit.Add("Jackfruit") ;
fruit.Add("Coconut") ;
fruit.Add("Banana") ;
// now remove the banana
fruit.RemoveAt(2);
Console.WriteLine(fruit.Count);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
14
Concatenation
You also can combine two lists and count their number by using the AddRange method.
using System;
using System.Collections.Generic;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
List<string> fruits = new List<string>();
fruits.Add(" apple ");
fruits.Add(" banana ");
fruits.Add(" orange ");
fruits.Add(" plum ");
fruits.Add(" guava ");
List<string> fruits2 = new List<string>();
fruits2.Add(" melon ");
fruits2.Add(" watermelon ");
fruits2.Add(" strawberry ");
fruits2.Add(" blueberry ");
fruits2.Add(" jackfruit ");
fruits2.Add(" dragonfruit ");
fruits.AddRange(fruits2);
Console.WriteLine(fruits.Count);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
11
Chapter Three
C# Conditionals

C# conditional statements generally are used when you have to execute or simply test a
particular action depending on a specific condition. C# allows programmers to test multiple
conditions. You can apply certain logical conditions from mathematics. You can test conditions
like less than, less than or equal to, equal to, greater than, greater than or equal to, and not equal
to. These conditions can be used to perform different actions to make different decisions. Just
like other programming languages C# can test a number of conditions like if, else if, else and
switch.
Let’s try a simple condition using the if condition. The condition will be true if the number
before the greater than sign is greater than 18. If not, the condition will be false.
using System.IO;
using System;
class Program1
{
static void Main()
{
if (50 > 18)
{
Console.WriteLine("The Number 50 is greater than 20");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The Number 50 is greater than 20
Now I will change the values and see what happens. If we put a lower number before the greater
than sign, the result will be a compilation error.
using System.IO;
using System;
class Program1
{
static void Main()
{
if (50 > 60)
{
Console.WriteLine("The Number 50 is greater than 60");
}
}
}
$mcs *.cs -out:main.exe
Compilation succeeded - 1 warning(s)
main.cs(10,9): warning CS0162: Unreachable code detected
$mono main.exe
In the following examples, I will test and see the results of other conditions I have talked about at
the start of the topic. The first on the line is the less than sign. It will show a simple message that
a particular number is less than the other one. See the following example. All you need to do is
to change the greater than sign to less than, and also change the statement.
using System.IO;
using System;
class Program1
{
static void Main()
{
if (50 < 60)
{
Console.WriteLine("The Number 50 is less than 60");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The Number 50 is less than 60
The next is the less than or equal to sign. I will also change the statement that will be displayed
to the user.
using System.IO;
using System;
class Program1
{
static void Main()
{
if (60 <= 60)
{
Console.WriteLine("The Number 50 is less than or equal to 60");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The Number 50 is less than or equal to 60
The conditional is the ‘greater than’ or ‘equal to’ option. I will change the sign and the statement
that will be printed by the compiler. See how it works.
using System.IO;
using System;
class Program1
{
static void Main()
{
if (70 >= 60)
{
Console.WriteLine("The Number 70 is less than or equal to 60");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The Number 70 is less than or equal to 60
In the next code snippet, I will make sure that the two numbers are equal.
using System.IO;
using System;
class Program1
{
static void Main()
{
if (60 >= 60)
{
Console.WriteLine("The Number 60 is less than or equal to 60");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The Number 60 is less than or equal to 60
There is another option that tells whether a number is equal to a number or not. It checks the
condition and displays the result in the form of a statement. The sign you will use for the purpose
is ==. I will replace the sign and change the statement to put this to work.
using System.IO;
using System;
class Program1
{
static void Main()
{
if (60 == 60)
{
Console.WriteLine("The Number 60 is equal to 60");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The Number 60 is equal to 60
There is a separate operator to check if two numbers are unequal or not. You will have to replace
the == sign with != and check out the results. See the following code snippet.
using System.IO;
using System;
class Program1
{
static void Main()
{
if (70 != 60)
{
Console.WriteLine("The Number 70 is not equal to 60");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The Number 70 is not equal to 60
Now that we have tested all the operators that you will have to use while writing conditional
statements, you can move on to practicing the first conditional statement that is the if statement.
You have seen the simplest use of the if statement. One thing to keep in mind is that you always
have to write if in lowercase letters. If you write it in uppercase letters, it will generate an error.
Let’s see how the error will look like if you change the case of letters.
using System.IO;
using System;
class Program1
{
static void Main()
{
If (70 != 60)
{
Console.WriteLine("The Number 70 is not equal to 60");
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 1 error(s), 0 warnings
main.cs(9,6): error CS1525: Unexpected symbol `{'
Now I will change both letters to uppercase.
using System.IO;
using System;
class Program1
{
static void Main()
{
IF (70 != 60)
{
Console.WriteLine("The Number 70 is not equal to 60");
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 1 error(s), 0 warnings
main.cs(9,6): error CS1525: Unexpected symbol `{'
You can see that in both attempts, the compilation failed and we had an error. One of the most
interesting features of the conditional statements is that it allows you to test different variables
and the condition between them. I will fill in the program with two variables a and b, and then I
will test them using different conditions that I have already mentioned.
using System.IO;
using System;
class Program1
{
static void Main()
{
int a = 30;
int b = 28;
if (a > b)
{
Console.WriteLine("The variable a is greater than b.");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The variable a is greater than b.
In the next code snippet, I will use the >= operator.
using System.IO;
using System;
class Program1
{
static void Main()
{
int a = 30;
int b = 28;
if (a >= b)
{
Console.WriteLine("The variable a is greater than b.");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The variable a is greater than b.
In the next example, I will use the less than operator on the same equation and the result will be
an error.
using System.IO;
using System;
class Program1
{
static void Main()
{
int a = 30;
int b = 28;
if (a < b)
{
Console.WriteLine("The variable a is greater than b.");
}
}
}
The result will be empty or an error as the compiler will be unable to process the information. In
the above examples, I have used two variables a and b to test if a is greater than b by using the
operator >. Then I wrote a statement that the program printed after testing the condition.
The Else Statement
You can use the else statement for specifying a certain block of code that you can execute if the
condition stands false. There are two blocks of code in the if-else statement. If the condition is
true, the first block of code executed. If the condition is false, the second block of code is
executed. In the following example, I will write a simple if-else statement that reads the time, test
the condition and displays a greetings message for the user. You can use this simple program in
your office or the reception of your business.
using System;
using System.Collections.Generic;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
int time = 15;
if (time < 16)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Good day.

In this example, the second block of code is executed because the condition turned out to be
false. In the next block of code, I will test the first block of code.
using System;
using System.Collections.Generic;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
int time = 18;
if (time < 16)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Good evening.

The Else If Statement


The else if statement is used for specifying a new condition if the first block of code is false. In
this conditional test, the first block of code is executed if the condition stands true. If the first
condition is false, the compiler moves on to the next block of code to test the condition. The
second block is executed and if the condition is true, the program stops there. If the second
condition is also false, the condition moves on to the third block of code and executes it. In the
following example, I will set up three conditionals with an else if at the end of the code to test
how the three blocks of code of work.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
int time = 24;
if (time < 8)
{
Console.WriteLine("Good morning. Hope you are doing well!");
}
else if (time < 16)
{
Console.WriteLine("Good day. Hope you are doing well!");
}
else
{
Console.WriteLine("Good evening. Hope you are doing well!");
}
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Good evening. Hope you are doing well!
In the above example you can see that 24 is greater than 8 so the first condition is false. The next
condition in the else if statement also stands False so that we can move on to the else condition
since the first two conditions are false. The message we get on the screen is Good evening. Hope
you are doing well! Let’s see change the time and see which condition stands true and how it
affects the code.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
int time = 20;
if (time < 21)
{
Console.WriteLine("Good morning. Hope you are doing well!");
}
else if (time < 16)
{
Console.WriteLine("Good day. Hope you are doing well!");
}
els e
{
Console.WriteLine("Good evening. Hope you are doing well!");
}
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Good morning. Hope you are doing well!
I have changed the time in the first condition so that the first condition stands true and we get the
Good morning message as a result. Let’s further change the value and see which condition stands
true as a result.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
int time = 15;
if (time < 8)
{
Console.WriteLine("Good morning. Hope you are doing well!");
}
else if (time < 16)
{
Console.WriteLine("Good day. Hope you are doing well!");
}
else
{
Console.WriteLine("Good evening. Hope you are doing well!");
}
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Good day. Hope you are doing well!
In this code snippet, the second condition stands true and the code is executed displaying the
Good day message.
Chapter Four
Interactive Programming

C# is an interesting language when it comes to writing a program that welcomes user input. You
have read about C# variables. These variables are used to store different types of input that is
entered by different users. This chapter will walk you through the process of accepting input
from users, storing data in a variable and then displaying different messages to the users. If you
want to display messages to users, you can use the Write() or WriteLine() methods that are built-
in in the C# language. Although the function of both methods is the same, the major difference
between the two is that they WriteLine() brings the cursor down to the next line after it has
displayed the message. The other method doesn’t give any such privilege to the users.

User Input
You have learned how to write Console.WriteLine() to display different types of output in a
program. There is another feature in C# that you can use to read input by a user. I will be using
Console.ReadLine() to receive the user input. This feature is very helpful for creating a program
that needs users to enter the input. The input is then stored in a variable. The program will then
print the value of the variable.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
// You are required to type the username and then press enter
Console.WriteLine("Please Enter the username: Jack");
// Now I will create a variable to store user input from your keyboard
string usrName = Console.ReadLine();
// Now I will print the value of this newly created variable, which will display this
input value
Console.WriteLine("The desired username is: " + usrName);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Please Enter the username: Jack
The desired username is:

Numerical Input
In the above program, the input type was string. The Console.ReadLine() will return a string. As
I have specified it, I will not be able to get value from another data type such as int. You can use
the following method to receive numerical input.
using System;
namespace MyApp
{
class Program1
{
static void Main(string[] args)
{
Console.WriteLine("You are required to enter your age:");
int yourage = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + yourage);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
You are required to enter your age: 56
Your age is: 0

C# Switch Statement
By using a switch statement, you can test a variable against values that you have allocated to a
list. Values are dubbed as cases, and the variable that is switched on is verified for switch case.
There are some rules that you must follow when you are writing switch statements.
The expression in a switch statement ought to be an integral type. There is no limit to the number
of cases in a switch. You should make sure to insert a colon to the end of each case. The
constant-expression and variable must be of the same data type in a switch. If the variable is
equal to the case, the execution will continue to the point you have included the break statement
in the code. The break statement terminates the switch. If you have forgotten to include a break
statement, you will see a compilation error. You must include a default case at the end of the
switch statement.
using System.IO;
using System;
class Program
{
static void Main()
{
int day = 1;
switch (day)
{
case 1:
Console.WriteLine("We will start construction of the office on Monday");
break;
case 2:
Console.WriteLine("We will start construction of the office on Tuesday");
break;
case 3:
Console.WriteLine("We will start construction of the office on Wednesday");
break;
case 4:
Console.WriteLine("We will start construction of the office on Thursday");
break;
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break;
case 6:
Console.WriteLine("We will start construction of the office on Saturday") ;
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
We will start construction of the office on Monday
I will enter different values to see how the switch statement executes different blocks of code
from the program.
using System.IO;
using System;
class Program1
{
static void Main()
{
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("We will start construction of the office on Monday");
break;
case 2:
Console.WriteLine("We will start construction of the office on Tuesday");
break;
case 3:
Console.WriteLine("We will start construction of the office on Wednesday") ;
break;
case 4:
Console.WriteLine("We will start construction of the office on Thursday");
break;
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break;
case 6:
Console.WriteLine("We will start construction of the office on Saturday");
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
We will start construction of the office on Wednesday
I will try a different value in the next example.
using System.IO;
using System;
class Program1
{
static void Main()
{
int day = 5;
switch (day)
{
case 1:
Console.WriteLine("We will start construction of the office on Monday");
break;
case 2:
Console.WriteLine("We will start construction of the office on Tuesday");
break;
case 3:
Console.WriteLine("We will start construction of the office on Wednesday");
break;
case 4:
Console.WriteLine("We will start construction of the office on Thursday");
break;
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break;
case 6:
Console.WriteLine("We will start construction of the office on Saturday");
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
We will start construction of the office on Friday
There is another example that will further explain how to write a switch statement and how to get
the results you want.
using System.IO;
using System;
class Program1
{
static void Main()
{
int day = 7;
switch (day)
{
case 1:
Console.WriteLine("We will start construction of the office on Monday");
break;
case 2:
Console.WriteLine("We will start construction of the office on Tuesday");
break;
case 3:
Console.WriteLine("We will start construction of the office on Wednesday");
break;
case 4:
Console.WriteLine("We will start construction of the office on Thursday");
break;
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break;
case 6:
Console.WriteLine("We will start construction of the office on Saturday") ;
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
We will start construction of the office on Sunday
Let me try an even number in the program. It will work as well as an odd number does.
using System.IO;
using System;
class Program1
{
static void Main()
{
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("We will start construction of the office on Monday");
break;
case 2:
Console.WriteLine("We will start construction of the office on Tuesday");
break;
case 3:
Console.WriteLine("We will start construction of the office on Wednesday") ;
break;
case 4:
Console.WriteLine("We will start construction of the office on Thursday");
break;
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break;
case 6:
Console.WriteLine("We will start construction of the office on Saturday");
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
We will start construction of the office on Thursday
The only thing you need to keep in mind is the number of blocks of code that you have in your
program. If you forget the number and enter something that exceeds the number of code blocks,
the result will be empty. Be careful because C# is a compiled language, which makes it hard to
spot an error or a missing line of code.
using System.IO;
using System;
class Program1
{
static void Main( )
{
int day = 9;
switch (day)
{
case 1:
Console.WriteLine("We will start construction of the office on Monday");
break;
case 2:
Console.WriteLine("We will start construction of the office on Tuesday");
break;
case 3:
Console.WriteLine("We will start construction of the office on Wednesday");
break;
case 4:
Console.WriteLine("We will start construction of the office on Thursday");
break;
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break;
case 6:
Console.WriteLine("We will start construction of the office on Saturday");
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe

The Break Keyword


The break keyword terminates the switch statement or loop statement. The loop doesn’t stop
until it stumbles upon a break statement. If you are running two loops in your program and the
break keyword is placed inside the inner loop, the break keyword will only terminate the inner
loop. There will be no effect on the outer loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
int day = 1;
switch (day)
{
case 1:
Console.WriteLine("We will start construction of the office on Monday");
break;
case 2:
Console.WriteLine("We will start construction of the office on Tuesday");
break;
case 3:
Console.WriteLine("We will start construction of the office on Wednesday");
break;
case 4:
Console.WriteLine("We will start construction of the office on Thursday");
break;
default:
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break;
case 6:
Console.WriteLine("We will start construction of the office on Saturday");
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
We will start construction of the office on Monday
Now I will change the value of the int keyword.
using System.IO;
using System;
class Program1
{
static void Main()
{
int day = 15;
switch (day)
{
case 1:
Console.WriteLine("We will start construction of the office on Monday");
break;
case 2:
Console.WriteLine("We will start construction of the office on Tuesday");
break;
case 3:
Console.WriteLine("We will start construction of the office on Wednesday");
break;
case 4:
Console.WriteLine("We will start construction of the office on Thursday");
break;
default:
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break;
case 6:
Console.WriteLine("We will start construction of the office on Saturday");
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
We will start construction of the office on Friday
You can see that I had entered 15 as the value but still I got the default result from the program.
Chapter Five
C# Loops

Loops keep executing a block of code until a specific condition has reached. Loops are really
handy because they tend to save time, cut down errors and they also make the code a lot more
readable. This chapter will walk you through the C# while loop and for loop. I will explain how
you can integrate them into your programs and how they will affect them.

C# While Loop
The while loop tends to loop through a block of code until a condition stands true. In the
following example, the code will keep running, until the condition is true. The while loop
initiates with the while keyword and it ought to include a Boolean conditional expression within
brackets that would return false or true. It also executes a code block until a specific conditional
expression returns false.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0; // this is the initialization
while (x < 50) // here is the condition
{
Console.WriteLine("x = {0}", x);
x++; // this is the increment
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
x=0
x=1
x=2
x=3
x=4
x=5
x=6
x=7
x=8
x=9
x = 10
x = 11
x = 12
x = 13
x = 14
x = 15
x = 16
x = 17
x = 18
x = 19
x = 20
x = 21
x = 22
x = 23
x = 24
x = 25
x = 26
x = 27
x = 28
x = 29
x = 30
x = 31
x = 32
x = 33
x = 34
x = 35
x = 36
x = 37
x = 38
x = 39
x = 40
x = 41
x = 42
x = 43
x = 44
x = 45
x = 46
x = 47
x = 48
x = 49
If we change the condition, the loop will stop at a previous or a later stage. I will set it at 25 in
the following example.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0; // this is the initialization
while (x < 25) // here is the condition
{
Console.WriteLine("x = {0}", x);
x++; // this is the incremen t
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
x=0
x=1
x=2
x=3
x=4
x=5
x=6
x=7
x=8
x=9
x = 10
x = 11
x = 12
x = 13
x = 14
x = 15
x = 16
x = 17
x = 18
x = 19
x = 20
x = 21
x = 22
x = 23
x = 24
If we change the operator from less than to greater than, the results will drastically change. There
will be a need to add the break keyword to stop the loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0; // this is the initialization
while (true) // here is the condition
{
Console.WriteLine("x = {0}", x);
x++; // this is the increment

if(x > 50)


break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
x=0
x=1
x=2
x=3
x=4
x=5
x=6
x=7
x=8
x=9
x = 10
x = 11
x = 12
x = 13
x = 14
x = 15
x = 16
x = 17
x = 18
x = 19
x = 20
x = 21
x = 22
x = 23
x = 24
x = 25
x = 26
x = 27
x = 28
x = 29
x = 30
x = 31
x = 32
x = 33
x = 34
x = 35
x = 36
x = 37
x = 38
x = 39
x = 40
x = 41
x = 42
x = 43
x = 44
x = 45
x = 46
x = 47
x = 48
x = 49
x = 50
The following is an example of an infinite while loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0; // this is the initialization
while (x > 0) // here is the condition
{
Console.WriteLine("x = {0}", x);
x++; // this is the increment

}
}
}
$mcs *.cs -out:main.exe
$mono main.exe

C# Nested While Loop


C# allows loops in another while loop as is displayed below. However, it is not recommended
that you use nested while loop as it would be hard to debug and maintain as well.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0, y = 1;
while (x < 30)
{
Console.WriteLine("x = {0}", x);
x++;
while (y < 30)
{
Console.WriteLine("y = {0}", y);
y++;
}
}

}
}
$mcs *.cs -out:main.exe
$mono main.exe
x=0
y=1
y=2
y=3
y=4
y=5
y=6
y=7
y=8
y=9
y = 10
y = 11
y = 12
y = 13
y = 14
y = 15
y = 16
y = 17
y = 18
y = 19
y = 20
y = 21
y = 22
y = 23
y = 24
y = 25
y = 26
y = 27
y = 28
y = 29
x=1
x=2
x=3
x=4
x=5
x=6
x=7
x=8
x=9
x = 10
x = 11
x = 12
x = 13
x = 14
x = 15
x = 16
x = 17
x = 18
x = 19
x = 20
x = 21
x = 22
x = 23
x = 24
x = 25
x = 26
x = 27
x = 28
x = 29

The Do-While Loop


The do-while is similar to a simple while loop except it tends to execute the block of code once.
It starts with the do keyword followed by another block of code, a Boolean expression and the
while keyword. The do-while keyword loop will stop execution exits when a Boolean condition
evaluates to false.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0;
do
{
Console.WriteLine("x = {0}", x);
x++;
} while (x < 40);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
x=0
x=1
x=2
x=3
x=4
x=5
x=6
x=7
x=8
x=9
x = 10
x = 11
x = 12
x = 13
x = 14
x = 15
x = 16
x = 17
x = 18
x = 19
x = 20
x = 21
x = 22
x = 23
x = 24
x = 25
x = 26
x = 27
x = 28
x = 29
x = 30
x = 31
x = 32
x = 33
x = 34
x = 35
x = 36
x = 37
x = 38
x = 39
You ought to specify the initialization from the loop and also specify the increment or decrement
counter within the do-while loop. You will be using the break or return keywords to exit out of
the do-while loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0;
do
{
Console.WriteLine("x = {0}", x);
x++;

if (x > 40)
break;
} while (x < 90);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
x=0
x=1
x=2
x=3
x=4
x=5
x=6
x=7
x=8
x=9
x = 10
x = 11
x = 12
x = 13
x = 14
x = 15
x = 16
x = 17
x = 18
x = 19
x = 20
x = 21
x = 22
x = 23
x = 24
x = 25
x = 26
x = 27
x = 28
x = 29
x = 30
x = 31
x = 32
x = 33
x = 34
x = 35
x = 36
x = 37
x = 38
x = 39
x = 40

C# Nested-do-while Loop
You also can nest a do-while loop in another do-while loop. This sounds a little bit complicating
but, in practice, it is quite easier to do.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0;
do
{
Console.WriteLine("The value of x is as follows: {0}", x);
int y = x;
x++;

do
{
Console.WriteLine("The value of y is as follows: {0}", y);
y++;
} while (y < 30);
} while (x < 40);
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The value of x is as follows: 0
The value of y is as follows: 0
The value of y is as follows: 1
The value of y is as follows: 2
The value of y is as follows: 3
The value of y is as follows: 4
The value of y is as follows: 5
The value of y is as follows: 6
The value of y is as follows: 7
The value of y is as follows: 8
The value of y is as follows: 9
The value of y is as follows: 10
The value of y is as follows: 11
The value of y is as follows: 12
The value of y is as follows: 13
The value of y is as follows: 14
The value of y is as follows: 15
The value of y is as follows: 16
The value of y is as follows: 17
The value of y is as follows: 18
The value of y is as follows: 19
The value of y is as follows: 20
The value of y is as follows: 21
The value of y is as follows: 22
The value of y is as follows: 23
The value of y is as follows: 24
The value of y is as follows: 25
The value of y is as follows: 26
The value of y is as follows: 27
The value of y is as follows: 28
The value of y is as follows: 29
The value of x is as follows: 1
The value of y is as follows: 1
The value of y is as follows: 2
The value of y is as follows: 3
The value of y is as follows: 4
The value of y is as follows: 5
The value of y is as follows: 6
The value of y is as follows: 7
The value of y is as follows: 8
The value of y is as follows: 9
The value of y is as follows: 10
The value of y is as follows: 11
The value of y is as follows: 12
The value of y is as follows: 13
The value of y is as follows: 14
The value of y is as follows: 15
The value of y is as follows: 16
The value of y is as follows: 17
The value of y is as follows: 18
The value of y is as follows: 19
The value of y is as follows: 20
The value of y is as follows: 21
The value of y is as follows: 22
The value of y is as follows: 23
The value of y is as follows: 24
The value of y is as follows: 25
The value of y is as follows: 26
The value of y is as follows: 27
The value of y is as follows: 28
The value of y is as follows: 29
The value of x is as follows: 2
The value of y is as follows: 2
The value of y is as follows: 3
The value of y is as follows: 4
The value of y is as follows: 5
The value of y is as follows: 6
The value of y is as follows: 7
The value of y is as follows: 8
The value of y is as follows: 9
The value of y is as follows: 10
The value of y is as follows: 11
The value of y is as follows: 12
The value of y is as follows: 13
The value of y is as follows: 14
The value of y is as follows: 15
The value of y is as follows: 16
The value of y is as follows: 17
The value of y is as follows: 18
The value of y is as follows: 19
The value of y is as follows: 20
The value of y is as follows: 21
The value of y is as follows: 22
The value of y is as follows: 23
The value of y is as follows: 24
The value of y is as follows: 25
The value of y is as follows: 26
The value of y is as follows: 27
The value of y is as follows: 28
The value of y is as follows: 29
The value of x is as follows: 3
The value of y is as follows: 3
The value of y is as follows: 4
The value of y is as follows: 5
The value of y is as follows: 6
The value of y is as follows: 7
The value of y is as follows: 8
The value of y is as follows: 9
The value of y is as follows: 10
The value of y is as follows: 11
The value of y is as follows: 12
The value of y is as follows: 13
The value of y is as follows: 14
The value of y is as follows: 15
The value of y is as follows: 16
The value of y is as follows: 17
The value of y is as follows: 18
The value of y is as follows: 19
The value of y is as follows: 20
The value of y is as follows: 21
The value of y is as follows: 22
The value of y is as follows: 23
The value of y is as follows: 24
The value of y is as follows: 25
The value of y is as follows: 26
The value of y is as follows: 27
The value of y is as follows: 28
The value of y is as follows: 29
The value of x is as follows: 4
The value of y is as follows: 4
The value of y is as follows: 5
The value of y is as follows: 6
The value of y is as follows: 7
The value of y is as follows: 8
The value of y is as follows: 9
The value of y is as follows: 10
The value of y is as follows: 11
The value of y is as follows: 12
The value of y is as follows: 13
The value of y is as follows: 14
The value of y is as follows: 15
The value of y is as follows: 16
The value of y is as follows: 17
The value of y is as follows: 18
The value of y is as follows: 19
The value of y is as follows: 20
The value of y is as follows: 21
The value of y is as follows: 22
The value of y is as follows: 23
The value of y is as follows: 24
The value of y is as follows: 25
The value of y is as follows: 26
The value of y is as follows: 27
The value of y is as follows: 28
The value of y is as follows: 29
The value of x is as follows: 5
The value of y is as follows: 5
The value of y is as follows: 6
The value of y is as follows: 7
The value of y is as follows: 8
The value of y is as follows: 9
The value of y is as follows: 10
The value of y is as follows: 11
The value of y is as follows: 12
The value of y is as follows: 13
The value of y is as follows: 14
The value of y is as follows: 15
The value of y is as follows: 16
The value of y is as follows: 17
The value of y is as follows: 18
The value of y is as follows: 19
The value of y is as follows: 20
The value of y is as follows: 21
The value of y is as follows: 22
The value of y is as follows: 23
The value of y is as follows: 24
The value of y is as follows: 25
The value of y is as follows: 26
The value of y is as follows: 27
The value of y is as follows: 28
The value of y is as follows: 29
The value of x is as follows: 6
The value of y is as follows: 6
The value of y is as follows: 7
The value of y is as follows: 8
The value of y is as follows: 9
The value of y is as follows: 10
The value of y is as follows: 11
The value of y is as follows: 12
The value of y is as follows: 13
The value of y is as follows: 14
The value of y is as follows: 15
The value of y is as follows: 16
The value of y is as follows: 17
The value of y is as follows: 18
The value of y is as follows: 19
The value of y is as follows: 20
The value of y is as follows: 21
The value of y is as follows: 22
The value of y is as follows: 23
The value of y is as follows: 24
The value of y is as follows: 25
The value of y is as follows: 26
The value of y is as follows: 27
The value of y is as follows: 28
The value of y is as follows: 29
The nested do-while loop is quite interesting because of the fact that the second loop iterates
through the first one. The x integer had 7 as a value so for each number of x, the first loop
iterated around 30 times as 30 was the value of y. You can copy the code and paste it in a
compiler. Change the value of x and you will realize how it will react. If you set the value of x at
100, the first do-while loop will iterate through for each of the 100 values of x. It is amazing.

C# For Loop
When you exactly know how many times you need to loop through a certain block of code, you
should run a for loop. Usually, there are three statements in a for loop. The first statement gets
executed once before the execution of the block of code. The second statement tends to define
the condition for the execution of the block of code. The third statement gets executed after the
block of code gets executed.
using System.IO;
using System;
class Program1
{
static void Main()
{
for (int x = 50; x < 65; x++)
{
Console.WriteLine(x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
The for loop has multiple sections that are usually separated by a semicolon. The first section is
labeled as the initializer, used to initialize a variable that acts as a local to the for loop. You
cannot access it outside of the loop. Its value can be zero or more than that. The second section
of the for loop is a Boolean expression that will be returning true or false. If a particular
expression tends to evaluate to true, it will execute the for loop. Otherwise the compiler will
execute the loop. The last section is known as an iterator. It defines the decremental or
incremental of the for loop variable. The following loop will execute a block of code 30 times.
You can increase or decrease the value to increase or decrease the number of repetitions.
using System.IO;
using System;
class Program1
{
static void Main()
{
for(int x = 0; x < 30; x++)
{
Console.WriteLine("The value of x is as follows: {0}", x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The value of x is as follows: 0
The value of x is as follows: 1
The value of x is as follows: 2
The value of x is as follows: 3
The value of x is as follows: 4
The value of x is as follows: 5
The value of x is as follows: 6
The value of x is as follows: 7
The value of x is as follows: 8
The value of x is as follows: 9
The value of x is as follows: 10
The value of x is as follows: 11
The value of x is as follows: 12
The value of x is as follows: 13
The value of x is as follows: 14
The value of x is as follows: 15
The value of x is as follows: 16
The value of x is as follows: 17
The value of x is as follows: 18
The value of x is as follows: 19
The value of x is as follows: 20
The value of x is as follows: 21
The value of x is as follows: 22
The value of x is as follows: 23
The value of x is as follows: 24
The value of x is as follows: 25
The value of x is as follows: 26
The value of x is as follows: 27
The value of x is as follows: 28
The value of x is as follows: 29
The int x = 0 acts as an initializer. I have defined the int variable x and afterward initialized it
with 0. The second section is the expression x < 30. If the condition stands true, the compiler will
execute the block of code. When the compiler has executed it, it will move on to the 3rd section
that is known as an iterator. The x++ is considered an incremental statement that would increase
the value of x by 1. It will check and test the conditional expression at each step and then repeat
the code until the conditional expression becomes false. In the next example, I will change the
value of the initializer. The loop will execute the code at the point from where the initializer
starts. I will change its value from zero to 10.
using System.IO;
using System;
class Program1
{
static void Main()
{
for(int x = 10; x < 30; x++)
{
Console.WriteLine("The value of x is as follows: {0}", x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The value of x is as follows: 10
The value of x is as follows: 11
The value of x is as follows: 12
The value of x is as follows: 13
The value of x is as follows: 14
The value of x is as follows: 15
The value of x is as follows: 16
The value of x is as follows: 17
The value of x is as follows: 18
The value of x is as follows: 19
The value of x is as follows: 20
The value of x is as follows: 21
The value of x is as follows: 22
The value of x is as follows: 23
The value of x is as follows: 24
The value of x is as follows: 25
The value of x is as follows: 26
The value of x is as follows: 27
The value of x is as follows: 28
The value of x is as follows: 29
However, you should make sure that the value of the initializer should not exceed the value of
the condition or the compiler will return an empty page.
using System.IO;
using System;
class Program1
{
static void Main()
{
for(int x = 40; x < 30; x++)
{
Console.WriteLine("The value of x is as follows: {0}", x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
There are some exceptions in regard to the for loop. The initializer, the conditions, and the
iterator sections are seen as optional. You can initialize the value even outside of the for loop.
After that you can define the condition and the iterator inside the block of code. See the
following example.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 10;
for(;;)
{
if (x < 30)
{
Console.WriteLine("The value of x is as follows: {0}", x);
x++;
}
else
break;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The value of x is as follows: 10
The value of x is as follows: 11
The value of x is as follows: 12
The value of x is as follows: 13
The value of x is as follows: 14
The value of x is as follows: 15
The value of x is as follows: 16
The value of x is as follows: 17
The value of x is as follows: 18
The value of x is as follows: 19
The value of x is as follows: 20
The value of x is as follows: 21
The value of x is as follows: 22
The value of x is as follows: 23
The value of x is as follows: 24
The value of x is as follows: 25
The value of x is as follows: 26
The value of x is as follows: 27
The value of x is as follows: 28
The value of x is as follows: 29
You can see that the results are the same. The for loop gives you the option to fill it in with any
kind of numerical data type like decimal, etc.
using System.IO;
using System;
class Program1
{
static void Main()
{
for (double d = 1.10D; d < 2.10; d+= 0.01D)
{
Console.WriteLine("The value of x: {0}", d);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The value of x: 1.1
The value of x: 1.11
The value of x: 1.12
The value of x: 1.13
The value of x: 1.14
The value of x: 1.15
The value of x: 1.16
The value of x: 1.17
The value of x: 1.18
The value of x: 1.19
The value of x: 1.2
The value of x: 1.21
The value of x: 1.22
The value of x: 1.23
The value of x: 1.24
The value of x: 1.25
The value of x: 1.26
The value of x: 1.27
The value of x: 1.28
The value of x: 1.29
The value of x: 1.3
The value of x: 1.31
The value of x: 1.32
The value of x: 1.33
The value of x: 1.34
The value of x: 1.35
The value of x: 1.36
The value of x: 1.37
The value of x: 1.38
The value of x: 1.39
The value of x: 1.4
The value of x: 1.41
The value of x: 1.42
The value of x: 1.43
The value of x: 1.44
The value of x: 1.45
The value of x: 1.46
The value of x: 1.47
The value of x: 1.48
The value of x: 1.49
The value of x: 1.5
The value of x: 1.51
The value of x: 1.52
The value of x: 1.53
The value of x: 1.54
The value of x: 1.55
The value of x: 1.56
The value of x: 1.57
The value of x: 1.58
The value of x: 1.59
The value of x: 1.6
The value of x: 1.61
The value of x: 1.62
The value of x: 1.63
The value of x: 1.64
The value of x: 1.65
The value of x: 1.66
The value of x: 1.67
The value of x: 1.68
The value of x: 1.69
The value of x: 1.7
The value of x: 1.71
The value of x: 1.72
The value of x: 1.73
The value of x: 1.74
The value of x: 1.75
The value of x: 1.76
The value of x: 1.77
The value of x: 1.78
The value of x: 1.79
The value of x: 1.8
The value of x: 1.81
The value of x: 1.82
The value of x: 1.83
The value of x: 1.84
The value of x: 1.85
The value of x: 1.86
The value of x: 1.87
The value of x: 1.88
The value of x: 1.89
The value of x: 1.9
The value of x: 1.91
The value of x: 1.92
The value of x: 1.93
The value of x: 1.94
The value of x: 1.95
The value of x: 1.96
The value of x: 1.97
The value of x: 1.98
The value of x: 1.99
The value of x: 2
The value of x: 2.01
The value of x: 2.02
The value of x: 2.03
The value of x: 2.04
The value of x: 2.05
The value of x: 2.06
The value of x: 2.07
The value of x: 2.08
The value of x: 2.09
The value of x: 2.1
Up until now you have seen how you can increment the value in the code with a for loop. You
also have the option to decrease the value of the variable by using the following code.
using System.IO;
using System;
class Program1
{
static void Main()
{
for(int x = 10; x > 0; x--)
{
Console.WriteLine("The value of x is: {0}", x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The value of x is: 10
The value of x is: 9
The value of x is: 8
The value of x is: 7
The value of x is: 6
The value of x is: 5
The value of x is: 4
The value of x is: 3
The value of x is: 2
The value of x is: 1
You also can push the figure into negatives by setting conditions that way. This can be handy
when you move on to building programs in C#. Some programs demand negative numbers,
calculated by a loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
for(int x = 10; x > -10; x--)
{
Console.WriteLine("The value of x is: {0}", x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The value of x is: 10
The value of x is: 9
The value of x is: 8
The value of x is: 7
The value of x is: 6
The value of x is: 5
The value of x is: 4
The value of x is: 3
The value of x is: 2
The value of x is: 1
The value of x is: 0
The value of x is: -1
The value of x is: -2
The value of x is: -3
The value of x is: -4
The value of x is: -5
The value of x is: -6
The value of x is: -7
The value of x is: -8
The value of x is: -9
Even if you have a condition, set at the higher number, you can exit the loop at will by using the
break keyword. I will take a previous example and enter in it the break keyword to see how it
stops the loop and allows you to exit the loop at will.
using System.IO;
using System;
class Program1
{
static void Main()
{
for (int x = 0; x < 14; x++)
{
if( x == 7 )
break;
Console.WriteLine("The Value of x is: {0}", x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The value of x is: 0
The value of x is: 1
The value of x is: 2
The value of x is: 3
The value of x is: 4
The value of x is: 5
The value of x is: 6
Even though the condition was set to loop through the block of code until it reached the figure
14, the loop stopped at 7.

Multiple Expressions
A for loop will also include multiple iterators and initializer statements that are usually separated
by a comma, as is shown below.
using System.IO;
using System;
class Program1
{
static void Main()
{
for (int x = 0, y = 0; x+y < 15; x++, y++)
{
Console.WriteLine("Value of x: {0}, Value of y: {1} ", x,y);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Value of x: 0, Value of y: 0
Value of x: 1, Value of y: 1
Value of x: 2, Value of y: 2
Value of x: 3, Value of y: 3
Value of x: 4, Value of y: 4
Value of x: 5, Value of y: 5
Value of x: 6, Value of y: 6
Value of x: 7, Value of y: 7
You also can add an iterator and an initializer in the for loop. This is a more complex but smart
form of writing a for loop in C#.

using System.IO;
using System;
class Program
{
static void Main()
{
int x = 0, y = 10;
for (Console.WriteLine($"Initializer: x={x}, y={y}");
x++ < y--;
Console.WriteLine($"Iterator: x={x}, y={y}"))
{
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Initializer: x=0, y=10
Iterator: x=1, y=9
Iterator: x=2, y=8
Iterator: x=3, y=7
Iterator: x=4, y=6
Iterator: x=5, y=5

C# Nested For Loop


You can nest a for loop inside of another for loop. The function is the same as with the while
loop. There is iteration. One loop simply runs like a normal loop while the other runs through
each value of the second loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
for (int x = 0; x < 10; x++)
{
for(int y =x; y < 6; y++)
Console.WriteLine("The value of x is: {0}, The value of Y is: {1} ", x,y);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The value of x is: 0, The value of Y is: 0
The value of x is: 0, The value of Y is: 1
The value of x is: 0, The value of Y is: 2
The value of x is: 0, The value of Y is: 3
The value of x is: 0, The value of Y is: 4
The value of x is: 0, The value of Y is: 5
The value of x is: 1, The value of Y is: 1
The value of x is: 1, The value of Y is: 2
The value of x is: 1, The value of Y is: 3
The value of x is: 1, The value of Y is: 4
The value of x is: 1, The value of Y is: 5
The value of x is: 2, The value of Y is: 2
The value of x is: 2, The value of Y is: 3
The value of x is: 2, The value of Y is: 4
The value of x is: 2, The value of Y is: 5
The value of x is: 3, The value of Y is: 3
The value of x is: 3, The value of Y is: 4
The value of x is: 3, The value of Y is: 5
The value of x is: 4, The value of Y is: 4
The value of x is: 4, The value of Y is: 5
The value of x is: 5, The value of Y is: 5

The C# Foreach Loop


There is another loop known as the foreach loop, which is exclusively used for looping through
an array. We had created an array of fruits in the previous chapters. I will take the same array and
integrate it in a foreach loop. The block of code will output all the elements in the fruits array by
deploying a foreach loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
foreach (string x in fruits)
{
Console.WriteLine(x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
guava
grapefruit
apple
banana
strawberry
blueberry
jackfruit
dragonfruit
peach
apricot
See how the for loop iterates through all items of an array. If you include in the code the length
property, you can fix how many times you want the for loop to iterate through the items inside
the array.
using System.IO;
using System;
class Program1
{
static void Main()
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
for (int x = 0; x < fruits.Length; x++)
{
Console.WriteLine(fruits[x]);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
guava
grapefruit
apple
banana
strawberry
blueberry
jackfruit
dragonfruit
peach
apricot
You can initialize the loop at a later point by changing the value of the initializer. Take a look at
the following example.
using System.IO;
using System;
class Program1
{
static void Main()
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
for (int x = 2; x < fruits.Length; x++)
{
Console.WriteLine(fruits[x]);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
apple
banana
strawberry
blueberry
jackfruit
dragonfruit
peach
apricot

C# Foreach Loop for Sorting Arrays


There are a big number of array methods available such as Sort(). This specific method sorts out
the array in alphabetical order or ascending order. You can use this special function if you are
creating a game in C#. Take the array of fruits. If your game has a vendor who sells fruits, you
can put the array in alphabetical order if a buyer asks about the types of fruits the vendor has.
The player will be able to display the list or speak through the vendor in the alphabetical order or
the ascending order. I will use both techniques in this section. The sorting function through the
foreach loop makes your games and program clean and interesting at the same time.
using System.IO;
using System;
class Program1
{
static void Main()
{
string[] fruits = {"guava", "grapefruit", "apple", "banana", "strawberry",
"blueberry", "jackfruit", "dragonfruit", "peach", "apricot"};
Array.Sort(fruits);
foreach (string x in fruits)
{
Console.WriteLine(x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
apple
apricot
banana
blueberry
dragonfruit
grapefruit
guava
jackfruit
peach
strawberry
For sorting an array in the ascending order, I will use an array of integers.
using System.IO;
using System;
class Program1
{
static void Main()
{
int[] myNum = {5, 2, 1, 3, 8, 7, 9};
Array.Sort(myNum);
foreach (int x in myNum)
{
Console.WriteLine(x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
1
2
3
5
7
8
9

C# Break and Continue Statements


I have already used the break statement in the previous chapters. I paired it up with the switch
statement. You also can use the break statement to move out of a loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
for (int x = 0; x < 10; x++)
{
if (x == 6)
{
break;
}
Console.WriteLine(x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
0
1
2
3
4
5
The next is the continue statement. It breaks an iteration once at the location you specify, and
then continue with the next iteration in the loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
for (int x = 0; x < 15; x++)
{
if (x == 6)
{
continue;
}
Console.WriteLine(x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
0
1
2
3
4
5
7
8
9
10
11
12
13
14
You can see that the loop skipped the number 6 as I had specified for not being iterated. You also
can use the break and continue statements in a similar fashion in the while loop. See the
following example of the break statement.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0;
while (x < 15)
{
Console.WriteLine(x);
x++ ;
if (x ==6)
{
break;
}
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
0
1
2
3
4
5
In the next example, I will use the continue statement.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0;
while (x < 20)
{
if (x == 10)
{
x++;
continue;
}
Console.WriteLine(x);
x++;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
0
1
2
3
4
5
6
7
8
9
11
12
13
14
15
16
17
18
19
Chapter Six
C# Methods

Programmers should be able to break big programs into smaller ones that are easier to handle.
The program should be short enough so that it can be easily readable. You can divide the class
code into little chunks that are labeled as methods. These are properly designed methods that can
simplify the job of writing complex programs. A method is just like a function that you might
have learned about in other programming languages. The only difference is that a method is part
of a C# class.
Methods are statements that allow a programmer to reuse an already written block of code. It
saves excessive use of memory and eases off the coding process. Methods also increase the
readability of code. In simple words, a method is also known as a collection of statements that
perform particular tasks and likewise return the results. There may come certain methods along
your way which don’t return anything.

Defining Methods
A method is generally defined with a name that is followed by a parenthesis. There also are some
predefined methods in C# such as the Main() which you have been acquainted with right from
the start of the book.
using System.IO;
using System;
class Program1
{
static void ThisMethod()
{
Console.WriteLine("Let's execute it!");
}
static void Main(string[] args)
{
ThisMethod();
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Let's execute it!
I have created a method, assign it a string value, and then called it in the end. In the above block
of code, the keyword static means that this method belongs to the Program1 class. The keyword
void means that the method doesn’t have a return value. You can call a method as many times as
you need to.
using System.IO;
using System;
class Program1
{
static void ThisMethod()
{
Console.WriteLine("Let's execute it!");
}
static void Main(string[] args)
{
ThisMethod();
ThisMethod();
ThisMethod();
ThisMethod();
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Let's execute it!
Let's execute it!
Let's execute it!
Let's execute it!

Parameters
You can pass on information to a method by using parameters. These parameters tend to act as
variables within the method. They are specified after the name of the method inside of the
parameters. Add many parameters as you want in your program. Separate them with a comma.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static void ThisMethod(string fname)
{
Console.WriteLine(fname + " will come to the class after playing football");
}
static void Main(string[] args)
{
ThisMethod("Jack");
ThisMethod("Tom");
ThisMethod("Fin");
ThisMethod("Jasmine");
ThisMethod("Sylvia");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Jack will come to the class after playing football
Tom will come to the class after playing football
Fin will come to the class after playing football
Jasmine will come to the class after playing football
Sylvia will come to the class after playing football
You also can add default parameters to the methods so that if you left them empty, it is filled by
the default parameters.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static void ThisMethod(string fname = " Donald will come to the class after playing
football")
{
Console.WriteLine(fname);
}
static void Main(string[] args)
{
ThisMethod();
ThisMethod();
ThisMethod();
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Donald will come to the class after playing football
Donald will come to the class after playing football
Donald will come to the class after playing football

Multiple Parameters
You can pass on more than one parameter to the method if you are building a complex program.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static void ThisMethod(string fname, int yearofbirth)
{
Console.WriteLine(fname + " was born in " + yearofbirth);
}
static void Main(string[] args)
{
ThisMethod("Jack", 2000);
ThisMethod("Tom", 1998);
ThisMethod("Sylvia", 1995);
ThisMethod("Yik", 1992);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Jack was born in 2000
Tom was born in 1998
Sylvia was born in 1995
Yik was born in 1992

Return Values
You can use the void keyword if you want the method to return a value. This technique can be
used in programs that involve mathematical calculations. See the following examples.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static int ThisMethod(int y)
{
return 10 + y;
}
static void Main(string[] args)
{
Console.WriteLine(ThisMethod(3));
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
13
I will now change the values and use a different mathematical operator to see the result.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static int ThisMethod(int y)
{
return 15 - y;
}
static void Main(string[] args)
{
Console.WriteLine(ThisMethod(50));
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
-35
You can use the operator for the multiplication of two digits.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static int ThisMethod(int y)
{
return 15 * y;
}
static void Main(string[] args)
{
Console.WriteLine(ThisMethod(50));
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
750
This last operator for the division.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static int ThisMethod(int y)
{
return 15 / y;
}
static void Main(string[] args)
{
Console.WriteLine(ThisMethod(50));
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
0

Two Parameters
Now I will be using two parameters in the same method.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static int ThisMethod(int y, int z)
{
return y + z;
}
static void Main(string[] args)
{
Console.WriteLine(ThisMethod(5, 6));
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
11
I will add more console statements to apply the method to different parameters.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static int ThisMethod(int y, int z)
{
return y - z;
}
static void Main(string[] args)
{
Console.WriteLine(ThisMethod(15, 6));
Console.WriteLine(ThisMethod(355, 6));
Console.WriteLine(ThisMethod(35, 6));
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
9
349
29
You can apply different mathematical operators to get the desired results. See the
following block of code.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static int ThisMethod(int y, int z)
{
return y * z;
}
static void Main(string[] args)
{
Console.WriteLine(ThisMethod(15, 6));
Console.WriteLine(ThisMethod(355, 6));
Console.WriteLine(ThisMethod(35, 6));
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
90
2130
210
Here comes division.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static int ThisMethod(int y, int z)
{
return y / z;
}
static void Main(string[] args)
{
Console.WriteLine(ThisMethod(15, 6));
Console.WriteLine(ThisMethod(355, 6));
Console.WriteLine(ThisMethod(35, 6));
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
2
59
5

Store Result
You have the option to store the result in a variable. Suppose you are creating a program in
which you invite users to fill in their input which you can view later on. You can direct the input
to a variable so that it would be easier to access whenever you need to view it.
using System.IO;
using System;
namespace MyApp
{
class Program1
{
static int ThisMethod(int y, int z)
{
return y / z;
}
static void Main(string[] args)
{

int x = ThisMethod(35 , 6);


Console.WriteLine(x);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
5
Chapter Seven
Object-Oriented Programming

This chapter will walk you through the ins and outs of object-oriented programming. C# supports
object-oriented programming. A class in C# is a bundle of data and functions that belong
together into a single tidy package. C# gives you the freedom to create classes and build
programs. These are basic concepts of OOP. You can model real-life objects on classes. A class
is like a user-defined blueprint from which you can create objects. A class, generally, combines
methods and fields into a single unit. Classes in C# support polymorphism.
A class contains a single keyword namely class, followed by an identifier, and each class may
have many different attributes. An object is a basic unit of object-oriented programming, and
may reflect any real-life entity. You can create many objects through C# programs. Many objects
tend to interact by invoking different methods. A particular object consists of a state which is
represented by different attributes of a particular object. It also reflects the properties of the
object. Another feature of the object is its behavior which is represented by different methods of
a particular object. It also reflects how an object responds. The third feature of a class is identity,
which gives a unique name to a particular object, and also enables it to interact with different
other objects present in the same class.
For example, a cat is an object. It rolls on the ground, sits and jumps. When we create an object
in a class, the class will be instantiated. All the different instances tend to share different
attributes and behavior of a class. There may be more than one instance in a class.

Creating C# Class
I will be using a new operator to initialize an object in a class.
using System;

// Declaration of class
public class Cat {

// Instance Variables
String cname;
String cbreed;
int cage;
String ccolor;

public Cat(String cname, String cbreed,


int cage, String ccolor)
{
this.cname = cname ;
this.cbreed = cbreed;
this.cage = cage;
this.ccolor = ccolor;
}

// This is Property 1
public String getName()
{
return cname;
}

// This is Property 2
public String getBreed()
{
return cbreed;
}
// This is Property 3
public int getAge()
{
return cage;
}

// This is Property 4
public String getColor()
{
return ccolor;
}

// Method 1
public String toString( )
{
return ("Hi this is " + this.getName()
+ ".\nYou will be pleased to know that my breed, age and color are " +
this.getBreed()
+ ", " + this.getAge() + ", " + this.getColor());
}

// This is the Main Method


public static void Main(String[] args)
{

// Mow I am Creating an object


Cat timmy = new Cat("Timmy", "ragdoll",6, "black.");
Console.WriteLine(timmy.toString());
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Hi this is Timmy.
You will be pleased to know that my breed, age and color are ragdoll, 6, black.
You can add as many instances to a single as you like. The one instance is timmy. Now I will
add more instances to the same class.
using System;

// Declaration of class
public class Cat {
// Instance Variables
String cname ;
String cbreed;
int cage;
String ccolor;

public Cat(String cname, String cbreed,


int cage, String ccolor)
{
this.cname = cname;
this.cbreed = cbreed;
this.cage = cage;
this.ccolor = ccolor;
}

// This is Property 1
public String getName()
{
return cname;
}

// This is Property 2
public String getBreed()
{
return cbreed;
}

// This is Property 3
public int getAge()
{
return cage;
}

// This is Property 4
public String getColor()
{
return ccolor;
}

// Method 1
public String toString()
{
return ("Hi this is " + this.getName()
+ ".\nYou will be pleased to know that my breed, age and color are as
followed : " + this.getBreed()
+ ", " + this.getAge() + ", " + this.getColor());
}

// This is the Main Method


public static void Main(String[] args)
{

// Mow I am Creating an object


Cat timmy = new Cat("Timmy", "ragdoll", 6 , "black.");
Console.WriteLine(timmy.toString()) ;

Cat tim = new Cat("Tim", "ragdoll", 9 , "white.");


Console.WriteLine(tim.toString()) ;

Cat hitman = new Cat("Hitman", "Savannah", 9 , "brown.");


Console.WriteLine(hitman.toString()) ;

Cat beamer = new Cat("Beamer", "sphynx", 8, "white.");


Console.WriteLine(beamer.toString()) ;
}

}
$mcs *.cs -out:main.exe
$mono main.exe
Hi this is Timmy.
You will be pleased to know that my breed, age and color are as followed : ragdoll, 6, black.
Hi this is Tim.
You will be pleased to know that my breed, age and color are as followed : ragdoll, 9, white.
Hi this is Hitman.
You will be pleased to know that my breed, age and color are as followed : Savannah, 9, brown.
Hi this is Beamer.
You will be pleased to know that my breed, age and color are as followed : sphynx, 8, white.
You can see that I have created four different objects through the process of instantiation. You
can add as many instances to the cat class as you like. This class has a single constructor.

The Car Class


I will model a car using the same instances.
using System;

// Declaration of class
public class Car {

// Instance Variables
String cname;
String cmodel;
int cmake;
String ccolor;

public Car(String cname, String cmodel,


int cmake, String ccolor)
{
this.cname = cname;
this.cmodel = cmodel;
this.cmake = cmake;
this.ccolor = ccolor;
}

// This is Property 1
public String getName()
{
return cname;
}

// This is Property 2
public String getModel()
{
return cmodel;
}

// This is Property 3
public int getMake()
{
return cmake;
}

// This is Property 4
public String getColor()
{
return ccolor;
}

// Method 1
public String toString()
{
return ("This car is " + this.getName()
+ ".\nIts model, year and color are as followed respectively : " +
this.getModel()
+ ", " + this.getMake() + ", " + this.getColor());
}

// This is the Main Method


public static void Main(String[] args)
{

// Mow I am creating an object


Car bmw = new Car("BMW", "X1", 2008 , "black.");
Console.WriteLine(bmw.toString()) ;

}
$mcs *.cs -out:main.exe
$mono main.exe
This car is BMW.
Its model, year and color are as followed respectively : X1, 2008, black.
Now I will add three more cars to the same class. You don’t have to change anything in the class.
All you are required to do is make the necessary changes in the instances that I have added. Fill it
in with the details by which you want to create more objects.
using System;

// Declaration of class
public class Car {

// Instance Variables
String cname;
String cmodel;
int cmake;
String ccolor;

public Car(String cname, String cmodel,


int cmake, String ccolor)
{
this.cname = cname;
this.cmodel = cmodel;
this.cmake = cmake;
this.ccolor = ccolor;
}

// This is Property 1
public String getName()
{
return cname;
}

// This is Property 2
public String getModel()
{
return cmodel;
}

// This is Property 3
public int getMake()
{
return cmake;
}

// This is Property 4
public String getColor()
{
return ccolor;
}

// Method 1
public String toString()
{
return ("This car is known as " + this.getName()
+ ".\nIts model, year and color are as followed respectively : " +
this.getModel()
+ ", " + this.getMake() + ", " + this.getColor());
}

// This is the Main Method


public static void Main(String[] args)
{

// Mow I am Creating an object


Car bmw = new Car("BMW", "X1", 2008 , "black.");
Console.WriteLine(bmw.toString()) ;

Car rangerover = new Car("Range Rover", "Velar", 2016 , "black.");


Console.WriteLine(rangerover.toString()) ;

Car audi = new Car("Audi", "A4 Sedan", 2014 , "black.");


Console.WriteLine(audi.toString()) ;

Car mercedes = new Car("Mercedes", "C-Class", 2019 , "white.");


Console.WriteLine(mercedes.toString()) ;

}
$mcs *.cs -out:main.exe
$mono main.exe
This car is known as BMW.
Its model, year and color are as followed respectively : X1, 2008, black.
This car is known as Range Rover.
Its model, year and color are as followed respectively : Velar, 2016, black.
This car is known as Audi.
Its model, year and color are as followed respectively : A4 Sedan, 2014, black.
This car is known as Mercedes.
Its model, year and color are as followed respectively : C-Class, 2019, white.

Class Members
In the following I will once again create a car class which will have two fields, one for the color
and the other for the speed.
using System;
namespace MyApp

{
class Cars
{
string ccolor = "white";
int cmaxSpeed = 150;
static void Main(string[] args)
{
Cars myObject = new Cars();
Console.WriteLine(myObject.ccolor);
Console.WriteLine(myObject.cmaxSpeed);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
white
150
If you want to let your users fill in the fields of the objects, you can fill them later on while you
are creating class objects.
using System;
namespace MyApp

{
class Cars
{
string ccolor ;
int cmaxSpeed ;
static void Main(string[] args)
{
Cars myObject = new Cars();
myObject.ccolor = "white";
myObject.cmaxSpeed = 150;
Console.WriteLine(myObject.ccolor);
Console.WriteLine(myObject.cmaxSpeed);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
white
150
I am now going to add two more fields to the same class to show how easy it is to add fields to a
single class.
using System;
namespace MyApp

{
class Cars
{
string ccolor ;
int cmaxSpeed ;
int cmake ;
string cmodel;
static void Main (string[] args)
{
Cars myObject = new Cars();
myObject.ccolor = "white";
myObject.cmaxSpeed = 150;
myObject.cmake = 2002;
myObject.cmodel = "BMW";
Console.WriteLine (myObject.ccolor) ;
Console.WriteLine (myObject.cmaxSpeed) ;
Console.WriteLine (myObject.cmake) ;
Console.WriteLine (myObject.cmodel) ;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
white
150
2002
BMW
You have already learned about how you can add different objects to a single class. There is
another method that you can use to create objects.
using System;
namespace MyApp

{
class Cars
{
string ccolor ;
int cmaxSpeed ;
int cmake ;
string cmodel;
static void Main (string[] args)
{
Cars BMW = new Cars();
BMW.ccolor = "Black" ;
BMW.cmaxSpeed = 200 ;
BMW.cmake = 2015 ;
BMW.cmodel = "Turismo" ;

Cars Audi = new Cars();


Audi.ccolor = "Black" ;
Audi.cmaxSpeed = 250 ;
Audi.cmake = 2019 ;
Audi.cmodel = "A4" ;

Cars Mercedes = new Cars();


Mercedes.ccolor = "Silver" ;
Mercedes.cmaxSpeed = 100 ;
Mercedes.cmake = 2013 ;
Mercedes.cmodel = "C-Class" ;

Console.WriteLine (BMW.ccolor) ;
Console.WriteLine (BMW.cmaxSpeed) ;
Console.WriteLine (BMW.cmake) ;
Console.WriteLine (BMW.cmodel) ;

Console.WriteLine (Audi.ccolor) ;
Console.WriteLine (Audi.cmaxSpeed) ;
Console.WriteLine (Audi.cmake) ;
Console.WriteLine (Audi.cmodel) ;

Console.WriteLine (Mercedes.ccolor) ;
Console.WriteLine (Mercedes.cmaxSpeed) ;
Console.WriteLine (Mercedes.cmake) ;
Console.WriteLine (Mercedes.cmodel) ;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Black
200
2015
Turismo
Black
250
2019
A4
Silver
100
2013
C-Class

Class Methods
Methods are inherent to classes and they are used to define how an object inside of a class
behaves. Just like the fields, you have the power to access different methods by using the dot
syntax. You must note that methods should be public. You must remember that you use the
method name along with the pair of parentheses and a semicolon. I will add a method to the cars
class mentioned above.
using System;
namespace MyApp

{
class Cars
{
string ccolor ;
int cmaxSpeed ;
int cmake ;
string cmodel;

public void fullThrot() // method


{
Console.WriteLine("These cars go from zero to hundred in five seconds! ");
}
static void Main (string[] args)
{

Cars BMW = new Cars();


BMW.ccolor = "Black" ;
BMW.cmaxSpeed = 210 ;
BMW.cmake = 2013 ;
BMW.cmodel = "A4" ;

Cars Audi = new Cars();


Audi.ccolor = "Black" ;
Audi.cmaxSpeed = 250 ;
Audi.cmake = 2019 ;
Audi.cmodel = "A4" ;

Cars Mercedes = new Cars();


Mercedes.ccolor = "Silver" ;
Mercedes.cmaxSpeed = 100 ;
Mercedes.cmake = 2013 ;
Mercedes.cmodel = "C-Class" ;

Cars myObj = new Cars();

myObj.fullThrot();

Console.WriteLine (BMW.ccolor) ;
Console.WriteLine (BMW.cmaxSpeed) ;
Console.WriteLine (BMW.cmake) ;
Console.WriteLine (BMW.cmodel) ;

Console.WriteLine (Audi.ccolor) ;
Console.WriteLine (Audi.cmaxSpeed) ;
Console.WriteLine (Audi.cmake) ;
Console.WriteLine (Audi.cmodel) ;

Console.WriteLine (Mercedes.ccolor) ;
Console.WriteLine (Mercedes.cmaxSpeed) ;
Console.WriteLine (Mercedes.cmake) ;
Console.WriteLine (Mercedes.cmodel) ;
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
These cars go from zero to a hundred in five seconds!
Black
210
2013
A4
Black
250
2019
A4
Silver
100
2013
C-Class
In the above example, the method was applied to all the instances that I had created. You can add
more instances to the class and also create and add more methods as well to experiment how far
you can go with the programming. It would really be fun and interesting.
You can create multiple classes to organize the program in a better and efficient way. For
example, you can create a separate class for field methods and another one for the execution.

C# Class Constructor
This is a special method that you can use to initialize objects. Its advantage is that it can be called
when a class object is created. You can use it to settle down the initial values for different fields.
using System;
namespace MyApp
{
// this will create a Car class
class Cars
{
public string cmodel; // This will create a field
// I will now Create the class constructor for the above-mentioned Cars class
public Cars( )
{
cmodel = "C-classic"; // This will set initial value for the model
}
static void Main(string[] args)
{
Cars Ford = new Cars();
Console.WriteLine(Ford.cmodel);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
C-classic
Try it with another model.
using System;
namespace MyApp
{
// this will create a Car class
class Cars
{
public string cmodel; // This will create a field
public string ccolor;
public int cmake;
// I will now Create the class constructor for the above mentioned Cars class
public Cars()
{
cmodel = "C-classic"; // This will set initial value for the model
ccolor = "White";
cmake = 2002 ;

}
static void Main(string[] args)
{
Cars Ford = new Cars();
Console.WriteLine(Ford.cmodel);
Console.WriteLine(Ford.ccolor);
Console.WriteLine(Ford.cmake);

Cars BMW = new Cars();


Console.WriteLine(BMW.cmodel);
Console.WriteLine(BMW.ccolor);
Console.WriteLine(BMW.cmake);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
C-classic
White
2002
C-classic
White
2002
The name of the constructor must match the name of the class. Also, there should not any return
type such as int or void. You can call the constructor when the object is created. All classes
possess constructors by default. If you don’t create one yourself, C# will do that for you.
You can pass on parameters to a constructor just like methods. See the following example.
using System;
namespace MyApp
{
class Cars
{
public string cmodel;

public Cars (string cmodelName)


{
cmodel = cmodelName;
}
static void Main(string[] args)
{
Cars Ford = new Cars("Mustang");
Console.WriteLine(Ford.cmodel);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Mustang

Multiple Parameters
You can add to the class as many parameters as you want to.
using System;
namespace MyApp
{
// this will create a Car class
class Cars
{
public string cmodel; // This will create a field
public string ccolor;
public int cmake;
// I will now Create the class constructor for the above mentioned Cars clas s
public Cars(string modelName, string modelColor, int modelMake)
{
cmodel = modelName ; // This will set initial value for the model
ccolor = modelColor ;
cmake = modelMake ;

}
static void Main(string[] args)
{
Cars Ford = new Cars("Mustang", "White", 2009);
Console.WriteLine(Ford.ccolor + " " + Ford.cmake + " " + Ford.cmodel);

Cars BMW = new Cars("BMW", "White", 2009);


Console.WriteLine(BMW.ccolor + " " + BMW.cmake + " " + BMW.cmodel);

Cars Merc = new Cars("Mercedes", "Black", 2010);


Console.WriteLine(Merc.ccolor + " " + Merc.cmake + " " + Merc.cmodel);

Cars Rangerover = new Cars("Rangerover", "Black", 2015);


Console.WriteLine(Rangerover.ccolor + " " + Rangerover.cmake + " " +
Rangerover.cmodel);

}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
White 2009 Mustang
White 2009 BMW
Black 2010 Mercedes
Black 2015 Rangerover

C# Properties
Combined with the properties is the concept of encapsulation. Encapsulation means that sensitive
data ought to be hidden from outside users. You can do this by declaring variables and fields as
private. You also can do that by providing public, set and get methods through properties to
update and access the value of a particular private field.
You only can access private variables inside the same class. No outside class can access it.
However, it can be done through properties. A property can be defined as a combination of a
method and a variable. There generally are two methods of property; one is the get and the other
is the set method.
using System;
namespace MyApp
{
class Cars
{
private string cname; // field
public string cName // property
{
get { return cname; }
set { cname = value; }
}
}
class Program1
{
static void Main(string[] args)
{
Cars thisObj = new Cars();
thisObj.cName = "BMW";
Console.WriteLine(thisObj.cName);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
BMW

We can change the object in the class with the same properties. See the following example.
using System;
namespace MyApp
{
class Cars
{
private string cname; // field
public string cName // property
{
get { return cname; }
set { cname = value; }
}
}
class Program1
{
static void Main(string[] args)
{
Cars thisObj = new Cars();
thisObj.cName = "Mercedes";
Console.WriteLine(thisObj.cName);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Mercedes
There is another way to write properties in a class. C# offers shorthand to automatically write
properties if you don’t want to define the field for the property. All you are required to write is
set; and get; within the scope of the property. In the following example, I will write the
properties automatically through shorthand. The difference between the two methods is that you
have to write less code that way.
using System;
namespace MyApp
{
class Cars
{
public string cName // property
{ get; set; }
}
class Program1
{
static void Main(string[] args)
{
Cars thisObj = new Cars();
thisObj.cName = "Mercedes";
Console.WriteLine(thisObj.cName);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Mercedes
Chapter Eight
C# Classes Explained Further

In C# you can inherit methods and fields from one class to another one. The concept of
inheritance concept is generally divided into two categories. One is named the Base Class which
is the class from which the other class is inherited. The other one is the Derived Class which
inherits properties from the parent class. To start the process of inheritance, you can use the :
symbol. In the following example, I will create one parent and one child class to show how you
can use them in real programming.
using System;
namespace MyApp
{
class Cars // base class (the parent class)
{
public string company = "Ford"; // The Cars field
public void honk() // The Cars method
{
Console.WriteLine("This is a brand new: ");
}
}
class MyCar : Cars // derived class (child)
{
public string cmodelName = "Mustang"; // Car field
}
class Program1
{
static void Main(string[] args)
{
// Create a myCar object
MyCar myCar = new MyCar();

myCar.honk();
Console.WriteLine(myCar.company + " " + myCar.cmodelName);
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
This is a brand new:
Ford Mustang
You can see that the parent class in the code is named as Cars while the child class in the code is
named as MyCar. Inheritance is considered an important aspect of Object-oriented Programming
(OOP). It is a particular mechanism in C# by which the child class is allowed to inherit different
features of the parent class. The parent class, whose features are inherited by the child class is
also known as the superclass or the base class. The child class which inherits the features of the
parent class is dubbed as a subclass or derived class or extended class. The subclass also can add
its own methods and fields besides inheriting methods and fields of the superclass.
The inheritance feature of C# classes tends to support the concept of reusability. When you
intend to create a new class and there already exists one which includes some code that you
want, you can derive a new class from an existing one. Take a look at another example of an
inherited class.
using System;
namespace MyApp {

class Program1 {

// data members
public string cname;
public string csubject;

public void creaders(string cname, string csubject)


{
this.cname = cname;
this.csubject = csubject;
Console.WriteLine("My name is " + cname);
Console.WriteLine("My most favorite subject is as follows: " + csubject);
}
}

class Myclass : Program1 {

// constructor of derived class


public Myclass()
{
Console.WriteLine("This is the child class or inherited class");
}
}

// Driver class
class Sudo1 {

// Main Method
static void Main(string[] args)
{

// creating object of derived class


Myclass g = new Myclass();

g.creaders("Tom", "Physics");
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
This is the child class or inherited class
My name is Tom
My most favorite subject is as follows: Physics

Polymorphism
The term polymorphism literally means “having multiple forms.”. If you have read chemistry,
you might have been acquainted with the term polymorphism. It occurs when many classes are
generally related to each other by the method of inheritance. Inheritance allows programmers to
inherit methods and fields from another class. Polymorphism makes use of the methods to
perform many tasks. This will allow them to perform one action in several ways.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
}
}
}
$mono main.exe
Our animal is making a sound at the moment
Our animal is making a sound at the moment
Our animal is making a sound at the moment
I am adding one more animal to the code.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
}
}
}
$mono main.exe
Our animal is making a sound at the moment
Our animal is making a sound at the moment
Our animal is making a sound at the moment
Our animal is making a sound at the moment
The output is not what you might be expecting. There is no mention of the type of sounds that
the animals had been producing. The base class method has overridden the derived class method
because they share the same name. You can add the virtual keyword to the method.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public virtual void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public override void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public override void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public override void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
Our animal is making a sound at the moment
The cat says: Meow Meow
The horse says: Neigh Neigh
The dog says: Bau Bau

Abstraction
Data abstraction is known as the process of hiding specific details and also showing the essential
information to the user. You can achieve abstraction with interfaces or abstract classes. You can
use the abstract keyword for methods and classes. An abstract class is a kind of restricted class
that cannot be used for the creation of an object. The abstract method can be used in the abstract
class. It lacks a body.
using System;
namespace MyApp
{
abstract class Animalkingdom // This is the Base class also known as the parent class
{
public abstract void theanimalSound();
public void csleep()
{
Console.WriteLine("Zzz");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public override void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public override void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public override void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{

Animalkingdom thisCat = new Cat(); // Creating a Pig object


thisCat.theanimalSound();
thisCat.csleep();
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
thisHorse.theanimalSound();
thisHorse.csleep();

Animalkingdom thisDog = new Dog();


thisDog.theanimalSound();
thisDog.csleep();
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The cat says: Meow Meow
Zzz
The horse says: Neigh Neigh
Zzz
The dog says: Bau Bau
Zzz

Interfaces
This is yet another method to achieve abstraction. Note the changes in the code.
using System;
namespace MyApp
{
interface IAnimalkingdom // This is the Base class also known as the parent class
{
void theanimalSound();
}
class Cat : IAnimalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : IAnimalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : IAnimalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{

IAnimalkingdom thisCat = new Cat(); // Creating a Pig object


thisCat.theanimalSound();
IAnimalkingdom thisHorse = new Horse(); // Creating a Dog object
thisHorse.theanimalSound() ;

IAnimalkingdom thisDog = new Dog();


thisDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
$mono main.exe
The cat says: Meow Meow
The horse says: Neigh Neigh
The dog says: Bau Bau

Error Messages
Classes are complex and lengthy which raises the stakes of committing blunders. If you miss a
curly brace or add an extra to the code, your program will return an error. As C# is a compiled
language, it gets pretty much tough to spot the error. Therefore you need to write it cleanly so
that if an error pops up, you can detect it and correct it. See the following error.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animakingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 2 error(s), 3 warnings
main.cs(15,15): warning CS0108: `MyApp.Cat.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(23,15): warning CS0108: `MyApp.Horse.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(31,15): warning CS0108: `MyApp.Dog.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(44,5): error CS0246: The type or namespace name `Animakingdom' could not be
found. Are you missing an assembly reference?
main.cs(49,5): error CS0841: A local variable `thisDog' cannot be used before it is
declared
I couldn’t add a single l to the word animal and the entire program is ruined with no hint of the
error. You have to scan the entire code and spot the error. See another misspelling error in the
following example.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.riteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 1 error(s), 3 warnings
main.cs(15,15): warning CS0108: `MyApp.Cat.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(23,15): warning CS0108: `MyApp.Horse.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(31,15): warning CS0108: `MyApp.Dog.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(25,13): error CS0117: `System.Console' does not contain a definition for
`riteLine'
/usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)
In the above error, I skipped a w in WriteLine. Can you understand the error message? Not at the
first look. But you can do that if you read the message twice or thrice. See what happens if the
names you used as variables don’t match. This one is more self-evident than the previous errors.
You may find it easier to detect them. However, you should read the error message and trying to
decipher its meaning. In this way, if something similar pops up on your screen during
programming, you will find it easier and quicker to fix. I will change the names of variables so
they don’t match.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
MyCat.theanimalSound();
MyHorse.theanimalSound();
MyDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 3 error(s), 3 warnings
main.cs(15,15): warning CS0108: `MyApp.Cat.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(23,15): warning CS0108: `MyApp.Horse.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(31,15): warning CS0108: `MyApp.Dog.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(47,5): error CS0103: The name `MyCat' does not exist in the current context
main.cs(48,5): error CS0103: The name `MyHorse' does not exist in the current context
main.cs(49,5): error CS0103: The name `MyDog' does not exist in the current context
A common error that you may confront while you are creating a program is caused by missing
any curly braces. See the following code.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
$mcs *.cs -out:main.exe
Compilation failed: 1 error(s), 0 warnings
main.cs(51,246): error CS1525: Unexpected symbol `end-of-file'
This error message clearly tells you that there is an unexpected symbol at the end of the file.
Now see the following error.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound( )
{
Console.WriteLine("The cat says: Meow Meow");

class Horse : Animalkingdom // This is the derived class (child)


{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound() ;
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 6 error(s), 0 warnings
main.cs(20,0): error CS1525: Unexpected symbol `class'
main.cs(21,0): error CS1525: Unexpected symbol `{'
main.cs(22,2): error CS1525: Unexpected symbol `public'
main.cs(22,10): error CS1547: Keyword `void' cannot be used in this context
main.cs(22,28): error CS1525: Unexpected symbol `('
main.cs(52,246): error CS1525: Unexpected symbol `end-of-file'
This one is a bit confusing because everything is alright at the end of the file. However, there are
a couple of wrong symbols in the file. You need to spot them and fill the vacant spot with the
correct symbols. See the following error and spot what is missing in the program.
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 4 error(s), 3 warnings
main.cs(15,15): warning CS0108: `MyApp.Cat.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(23,15): warning CS0108: `MyApp.Horse.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(31,15): warning CS0108: `MyApp.Dog.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(9,5): error CS0103: The name `Console' does not exist in the current context
main.cs(17,5): error CS0103: The name `Console' does not exist in the current context
main.cs(25,5): error CS0103: The name `Console' does not exist in the current context
main.cs(33,5): error CS0103: The name `Console' does not exist in the current context
A hint is that something is missing at the top of the file. This happens more often when you are
copying code from one file to another. If you see the error on the screen that the compiler has
found an unexpected symbol in the program, you should know that you might have missed a
semicolon or a curly brace. The following error message does tell you that a semicolon is either
missing or is in excess, but it doesn’t tell where the error lies. Just like other errors, you have to
find it yourself. Take a look and try to find the error.
using System
namespace MyApp
{
class Animalkingdom; // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound( )
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 7 error(s), 0 warnings
main.cs(3,0): error CS1525: Unexpected symbol `namespace', expecting `.', `::', `;', `<', or
`='
main.cs(5,19): error CS1525: Unexpected symbol `;', expecting `(', `:', `{', or `where'
main.cs(7,9): error CS1525: Unexpected symbol `void', expecting `(', `:', `{', or `where'
main.cs(9,4): error CS1525: Unexpected symbol `Console', expecting `(', `:', `{', or
`where'
main.cs(9,21): error CS1525: Unexpected symbol `(', expecting `(', `:', `{', or `where'
main.cs(10,3): error CS1514: Unexpected symbol `}', expecting `.' or `{'
main.cs(52,0): error CS1525: Unexpected symbol `}'
So I added an extra semicolon to the program; the compiler returned this in the form of an error.
Now in the next example, I will remove a couple of semicolons. See the error message and try to
familiarize yourself with this error message so that you may fix this kind of problem head-on
while you are writing a program.
using System
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment")
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow")
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh" )
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 4 error(s), 0 warnings
main.cs(3,0): error CS1525: Unexpected symbol `namespace', expecting `.', `::', `;', `<', or
`='
main.cs(10,3): error CS1002: ; expected
main.cs(18,3): error CS1002: ; expected
main.cs(26,3): error CS1002: ; expected
Another common mistake that programmers make is that they miss out on writing the right upper
case and lower case letters. In the following error message, I will deliberately miss out on using
capital letters where I must use them. See the error message and familiarize yourself with it to fix
it if the same pops up while you are writing a program. See the following example.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new cat(); // Creating a Pig object
Animalkingdom thisHorse = new horse(); // Creating a Dog object
Animalkingdom thisDog = new dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 3 error(s), 3 warnings
main.cs(15,15): warning CS0108: `MyApp.Cat.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(23,15): warning CS0108: `MyApp.Horse.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(31,15): warning CS0108: `MyApp.Dog.theanimalSound()' hides inherited
member `MyApp.Animalkingdom.theanimalSound()'. Use the new keyword if hiding
was intended
main.cs(7,15): (Location of the symbol related to previous warning)
main.cs(42,33): error CS0246: The type or namespace name `cat' could not be found. Are
you missing an assembly reference?
main.cs(43,35): error CS0246: The type or namespace name `horse' could not be found.
Are you missing an assembly reference?
main.cs(44,33): error CS0246: The type or namespace name `dog' could not be found.
Are you missing an assembly reference?
The next error is a simple one; that’s why you should decipher the error message yourself and try
to spot it.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound
{
Console.WriteLine("Our animal is making a sound at the moment");
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound
{
Console.WriteLine("The cat says: Meow Meow");
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound
{
Console.WriteLine("The horse says: Neigh Neigh");
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound
{
Console.WriteLine("The dog says: Bau Bau");
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat; // Creating a Pig object
Animalkingdom thisHorse = new Horse; // Creating a Dog object
Animalkingdom thisDog = new Dog;

thisAnimal.theanimalSound ;
thisCat.theanimalSound;
thisHorse.theanimalSound;
thisDog.theanimalSound;
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 11 error(s), 0 warnings
main.cs(7,10): error CS0547: `MyApp.Animalkingdom.theanimalSound': property or
indexer cannot have void type
main.cs(9,5): error CS1014: A get or set accessor expected
main.cs(15,10): error CS0547: `MyApp.Cat.theanimalSound': property or indexer cannot
have void type
main.cs(17,5): error CS1014: A get or set accessor expected
main.cs(23,10): error CS0547: `MyApp.Horse.theanimalSound': property or indexer
cannot have void type
main.cs(25,5): error CS1014: A get or set accessor expected
main.cs(31,10): error CS0547: `MyApp.Dog.theanimalSound': property or indexer
cannot have void type
main.cs(33,5): error CS1014: A get or set accessor expected
main.cs(42,35): error CS1525: Unexpected symbol `;', expecting `(', `[', or `{'
main.cs(43,39): error CS1525: Unexpected symbol `;', expecting `(', `[', or `{'
main.cs(44,35): error CS1525: Unexpected symbol `;', expecting `(', `[', or `{'
I will explain in this error the absence of the inverted commas. Sometimes they are too much that
you lose track of them while writing a program. See the following error message and try to
understand it so that you may fix it in the future.
using System;
namespace MyApp
{
class Animalkingdom // This is the Base class also known as the parent class
{
public void theanimalSound()
{
Console.WriteLine("Our animal is making a sound at the moment);
}
}
class Cat : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The cat says: Meow Meow');
}
}
class Horse : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The horse says: Neigh Neigh);
}
}
class Dog : Animalkingdom // This is the derived class (child)
{
public void theanimalSound()
{
Console.WriteLine("The dog says: Bau Bau);
}
}
class Program1
{
static void Main(string[] args)
{
Animalkingdom thisAnimal = new Animalkingdom(); // Creating an Animal object
Animalkingdom thisCat = new Cat(); // Creating a Pig object
Animalkingdom thisHorse = new Horse(); // Creating a Dog object
Animalkingdom thisDog = new Dog();

thisAnimal.theanimalSound();
thisCat.theanimalSound();
thisHorse.theanimalSound();
thisDog.theanimalSound();
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 12 error(s), 0 warnings
main.cs(9,67): error CS1010: Newline in constant
main.cs(10,2): error CS1525: Unexpected symbol `}', expecting `)' or `,'
main.cs(10,3): error CS1002: ; expected
main.cs(17,49): error CS1010: Newline in constant
main.cs(18,2): error CS1525: Unexpected symbol `}', expecting `)' or `,'
main.cs(18,3): error CS1002: ; expected
main.cs(25,52): error CS1010: Newline in constant
main.cs(26,2): error CS1525: Unexpected symbol `}', expecting `)' or `,'
main.cs(26,3): error CS1002: ; expected
main.cs(33,46): error CS1010: Newline in constant
main.cs(34,2): error CS1525: Unexpected symbol `}', expecting `)' or `,'
main.cs(34,3): error CS1002: ; expected
In the following error code, I will use the switch statement to see which kind of errors you may
experience. I will change the case of keywords like a switch in the program. See the following
example.
using System.IO;
using System;
class Program
{
static void Main()
{
Int day = 1;
Switch (day)
{
Case 1:
Console.WriteLine("We will start construction of the office on Monday");
break;
Case 2:
Console.WriteLine("We will start construction of the office on Tuesday");
break;
Case 3:
Console.WriteLine("We will start construction of the office on Wednesday");
break;
case 4:
Console.WriteLine("We will start construction of the office on Thursday");
break;
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break ;
case 6:
Console.WriteLine("We will start construction of the office on Saturday");
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 15 error(s), 0 warnings
main.cs(10,0): error CS1525: Unexpected symbol `{'
main.cs(11,7): error CS1525: Unexpected symbol `1'
main.cs(11,8): error CS1525: Unexpected symbol `:'
main.cs(14,7): error CS1525: Unexpected symbol `2'
main.cs(14,8): error CS1525: Unexpected symbol `:'
main.cs(17,7): error CS1525: Unexpected symbol `3'
main.cs(17,8): error CS1525: Unexpected symbol `:'
main.cs(20,2): error CS1525: Unexpected symbol `case'
main.cs(20,8): error CS1525: Unexpected symbol `:'
main.cs(23,2): error CS1525: Unexpected symbol `case'
main.cs(23,8): error CS1525: Unexpected symbol `:'
main.cs(26,2): error CS1525: Unexpected symbol `case'
main.cs(26,8): error CS1525: Unexpected symbol `:'
main.cs(29,2): error CS1525: Unexpected symbol `case'
main.cs(29,8): error CS1525: Unexpected symbol `:'
In the following code sample, you will see what happens if you misspell the keywords in a
program.
using System.IO;
using System;
class Program1
{
stati vid Main()
{
int day = 1;
switch (day)
{
case 1:
Consle.WriteLine("We will start construction of the office on Monday");
break;
case 2:
Consle.WriteLine("We will start construction of the office on Tuesday");
break;
case 3:
Consle.WriteLine("We will start construction of the office on Wednesday");
break;
case 4:
Consle.WriteLine("We will start construction of the office on Thursday");
break;
case 5:
Console.WriteLine("We will start construction of the office on Friday");
break;
case 6:
Console.WriteLine("We will start construction of the office on Saturday");
break;
case 7:
Console.WriteLine("We will start construction of the office on Sunday");
break;
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 2 error(s), 0 warnings
main.cs(6,18): error CS1519: Unexpected symbol `Main' in class, struct, or interface
member declaration
main.cs(6,15): error CS1520: Class, struct, or interface method must have a return type
In the next example, you will see what error message is likely to be displayed if you miss out on
a symbol in a while loop.
using System.IO;
using System;
class Program1
{
static void Main()
{
int x = 0 // this is the initialization
while (x < 50) // here is the condition
{
Console.WriteLine("x = {0}", x);
x++; // this is the increment
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 4 error(s), 0 warnings
main.cs(10,0): error CS1525: Unexpected symbol `while'
main.cs(12,34): error CS0128: A local variable named `x' is already defined in this scope
main.cs(12,34): error CS1525: Unexpected symbol `)'
main.cs(17,0): error CS1525: Unexpected symbol `}'
A semicolon was missing in the above code sample. In the next example, I will remove () from
the while loop and see what results I receive.
using System.IO;
using System;
class Program1
{
static void Main
{
int x = 0; // this is the initialization
while (x < 50) // here is the condition
{
Console.WriteLine("x = {0}", x);
x++; // this is the increment
}
}
}
$mcs *.cs -out:main.exe
Compilation failed: 3 error(s), 0 warnings
main.cs(6,12): error CS0547: `Program1.Main': property or indexer cannot have void
type
main.cs(8,8): error CS1014: A get or set accessor expected
main.cs(17,0): error CS1525: Unexpected symbol `}'
Chapter Nine
Writing Secure Code

Programming is generally described as the process which leads a computing problem from the
original formulation to the executable program. The process generally involves different
activities such as analysis, developing understanding, generation of algorithms, and verification
of the essential algorithms including accuracy and the utilization of resources. It also includes the
coding of different algorithms in a particular programming language.
Many C# developers don’t write unit test methods for different non-public assemblies. C#
enables you to boost visibility in between assembly internals and other different assemblies.
Security is considered a big topic when it comes to coding and programming. When you have an
application in C#, the first thing you need to do is secure from application from being attacked
by malicious hackers or from being used for things it was not meant to be used for. At the start of
the electronic age, security is normally performed by the method of obfuscation. If you have
built an application and you want it to stay secure, you can hide it and no one will ever know
where to find it. It would remain secure.
Security is and ought to be considered an integral part of every system you write. It is possible
that your application may not contain any sensitive data, but will be used to get other information
that is saved on your machine? Attackers might use it to gain access to a network that you have
deemed forbidden.
The two major parts of security are known as authentication and authorization. Authentication is
defined as the process of making sure that a user has the authentication to access the application.
The most widely known method of authentication requires a username and a password. You also
can use a thumbprint method for the purpose. Authentication suggests that you ensure that a user
possesses the authority to do what he or she is requesting to do. File permissions are considered a
good example of this. Some app developers don’t let users delete system-only files.
However, there is more to security than merely usernames and passwords. This chapter will walk
you through how to make your C# programs secure from outside attacks.

Secure Design
Security usually takes a good amount of work while you are designing software. If you break
down the process into tiny chunks, you will find out that it would be a lot easier to accomplish.
You have to take up a systematic approach to ensure the security of your systems. Different
applications possess different artifacts that require protection, but all applications usually have
something that needs to be secured. If there is a database in your application, it is the most
important item for protection.
The server should be high-rated if you want better security. Even if you build a simple program
that is a single-user application, you must not let any outsider to a user the application for
breaking into the computer of the user.

Documentation
Describe what your application is. The description becomes a functional overview of the
application. Describe how your application accomplishes the tasks at the highest level. If you
take a look at a Software Architecture Overview diagram, you will know which services and
machines have what job to do.
When you have created the document that describes the job of the software, you must break out
different individual pieces of the software. If you have set up the software in the component
fashion, the methods and classes show functional decomposition. The final result of this breaking
down the software is taking a look at the individual pieces and decide which components must be
protected.
When you have created a list of components that you ought to protect, you must tackle the tough
part. You need to put two and two together. If your application tends to connect to a database,
you must imagine that this connection needs to be intercepted by some third party.

Threat Model
You must create a threat model for which you have to categorize different potential threats to the
software. The easiest way to remember different categories of threats is by using the STRIDE
method.
Security is more often described as a negative property. You can label a system as secure if there
is no danger of attack. To access the system’s security, you need to look at and analyze all the
possible threats that are posed against your system. The STRIDE model is considered a useful
tool to help you classify these threats.
Microsoft develops it to classify potential threats on the server. Each alphabet in the word
STRIDE represents a potential threat.
Spoofing
Most of the security systems tend to rely on the authentication and identification of the users.
Spoofing attacks largely consist of using another user’s credentials without his or her knowledge.
Typical spoofing threats target weak authentication mechanisms. It targets those that have
simple passwords like 4 digit password. Attackers access personal information quite easily such
as the place of birth and the date of birth.
Tampering
Only authorized users are allowed to modify a system or the data it uses. If an attacker can
tamper it, it results in some serious consequences on the usage of the system. If the attacker can
add or remove a bunch of functional elements, for instance, some important data gets destroyed
or modified.
Repudiation
Attackers need to hide malicious activity to avoid getting detected or blocked. They may try to
repudiate the actions they have already performed such as erasing them from the logs or by
spoofing different credentials of any other user.
Information Disclosure
Many systems keep confidential information. Attackers aim at securing and getting hold of that
information. It also is known as data breaches.
Denial of Service
A system is deployed generally for a particular purpose whether it be a banking application or
any kind of integrated media management that is installed on a vehicle. In some cases, attackers
will show interest in the prevention of regular users for accessing the system. This can be for
blackmailing a person or for extortion of money from the owner of a system. Ransomware is an
example of such a threat.
Privilege
Once a system identifies a user, they have some kind of privilege which is that they are
authorized for performing certain actions, but not all of the actions. An attacker might try to get
additional privileges by spoofing a user with higher privileges or just by tampering the system
and changing their respective privileges.
All these threats ought to be determined in a certain outline under the functions that would
expose the threat. The strategy gives you a discrete list of threats and also focuses the security
hardening on different parts of the application that would pose the greatest security risk.
You should rate the risk by defining what the potential for damage is. For example, you may
calculate the dollar cost of the company for the breach. You ought to calculate how far a
potential hacker can go in terms of exploiting our system. You also should calculate the number
of users who have been affected. Try to find out who they are. The level of difficulty by which
you can discover the threat also ought to be determined.

Common Mistakes
The most common mistake programmers make is using string concatenation technique in the
wrong way. In other programming languages, concatenation can be done by inserting a plus sign
between the strings. This is considered inefficient and fragile. C# offers StringBuilder method to
perform the same task. The method is useful for complex operations. For example, you can
deploy it if you have to concatenate one long list to another and display the output to the user or
channelize the output to a database for storage purposes.
The second most common mistake that programmers make is that they don’t log errors when
they are writing the code. You have seen that I carefully documented different kinds of error
messages that I received from the compiler, and presented them to you so that you can use them
as a reference whenever you see the same, and fix them. If you develop the habit of documenting
the error messages whenever the compiler throws one, you will be able to fix the errors in the
code faster than before. Log your errors and the next you will see one, you will know its
background.
The third mistake that can be easily avoided is using var despite knowing which data type is in
use. When you use var, you allow the compiler to decide upon the datatype of the variable. The
fact is that compiler may be wrong. It will not always detect the correct datatype. Better define
the datatype yourself. Besides decreasing the chance of error, it will improve the readability of
your code, which is better if a colleague in the office has to read your code for the purpose of its
betterment.
Conclusion

Now that you have made it to the end of the book, you should be able to practice the different
features of C# programming. The key lies in practicing more by using different variables and
methods. Experiment with the code and learn each step.
C# offers an immense variety of toolsets and different frameworks that you can use while
programming. Microsoft generally backs all these frameworks and toolsets. Any developer will
admit that Visual Studio is feature-rich and powerful development environments that exist in the
market. The .NET framework offers hundreds of libraries for the building of websites, working
with the file system and the implementation of security.
I hope that this book has equipped you with the right skills and techniques and that you will be
able to program by using C#. You can keep this book as a pocketbook that you can use whenever
you are writing or practicing a code. Take the sample codes as the right track to follow and
gradually learn. I have tried to keep the context of the book as simple and easy-to-read as I could
so that even a beginner may find in it the right material.

This book dealt with the most basic topics like strings, variables, data types, and other stuff like
that. You learned about the basics of C# like strings, substrings, and different properties of
strings. Strings and integers are the most common data types that you might have noticed on
several occasions in the code. I have used both of them in almost all of my codes. You have
learned about C# loops such as the while loop, do-while loop, for loop, and foreach loop. These
topics are really interesting and can help you create programs that involve mathematical
calculations. These types of elements are used in the programs that are created for cash counters.
They will do the math for you in the blink of an eye. You have also learned about C# arrays and
lists which are immensely helpful when you are creating a game in C#. You can allow the
players to be more interactive while playing the game. You have also learned about the most
important aspect of C# which is object-oriented programming (OOP). This chapter contained
classes that are used to model real-life objects in the world of programming. I created a dog, a
cat, and a car class for you to understand how you can create different objects and give them
certain features so that they can fulfill your specific programming needs. I hope you have
practiced this section quite well, and even if you have not, you should do that even if you have
now completed the book. You must be an expert at OOP; that’s why I have dedicated two
chapters for this section. C# classes have different features and you must get yourself acquainted
with them before you start writing your program.
References

http://www.scfilmvideo.com/download/temp/0470563486.For.Dummies.CSharp.2010.All-in-
One.For.Dummies.Apr.2010.pdf
https://www.w3schools.com/cs/cs_arrays.asp
https://www.w3schools.com/cs/cs_for_loop.asp
https://www.w3schools.com/cs/cs_user_input.asp ’
https://www.w3schools.com/cs/cs_conditions.asp
https://www.learncs.org/en/Lists#:~:text=Lists%20in%20C%23%20are%20very,called%20numbers%20which%
https://www.tutorialsteacher.com/csharp/csharp-list
https://www.w3schools.com/cs/cs_break.asp
https://www.w3schools.com/cs/cs_oop.asp
https://www.freelancer.com/community/articles/top-16-c-programming-tips-tricks
https://www.w3schools.com/cs/cs_classes.asp
https://www.w3schools.com/cs/cs_inheritance.asp
https://www.futurelearn.com/courses/cyber-security/0/steps/19631
C#
Advanced Guide to Learn C# Programming Effectively

BENJAMIN SMITH
Introduction

Object-oriented programming is like a rabbit hole; once you start to explore it, the tunnel only
seems to get deeper and deeper. This is especially true because of the family of programming
languages whose cores are based on object-oriented techniques and principles. C++, C, Java,
Javascript, PHP, Visual Basic, Microsoft .NET, Ruby, Scala, and a bunch of other programming
languages are all classified as ‘OOPL’ (Object-Oriented Programming Languages). In this
language family, C# is similar to that sibling who is difficult to get along with but incredibly
resourceful. C# is alluring and fascinating to some people, while to others, it is a real hassle to
learn and work with this language, but none of these two people at the opposite ends of the
spectrum are to blame.
People familiar with mainstream OOPL, such as C++, will find that C# has all those bells and
whistles that you would find in other object-oriented languages, ultimately making it easier to
learn C#, but even with these similarities, the implementation of the same techniques, tools, and
concepts are radically different, and on top of that, C# does not have one defined IDE, anyway.
At the same time, you can argue that no programming language has one IDE that’s better than
the rest. Still, in the case of C#, the result is an inconsistency in the programming experience, not
the case for other languages. Hence, trying to teach the reader a universal set of techniques and
practices is quite literally impossible. Even the fundamental concepts may be different, even
though you may be familiar with them from other object-oriented languages.
For this very reason, the first chapter of the book is essentially a review of the most important
programming concepts in C#. In this way, since all the readers will likely read this chapter before
moving on, everyone will have the same idea of the concepts that are being explained and used
in the upcoming chapters. This is very important because literally, every discussion being made
after chapter 1 builds upon the concepts that are highlighted at the very beginning. Even if the
reader already knows about all the concepts discussed in the first chapter, the chapter itself does
not become useless because it will still serve as an opportunity to review the knowledge that they
already possess. If there’s something that is not clear or is ambiguously explained, then do a brief
web-search. There’s a high chance that you might just need a small detail to understand what’s
being discussed in the topic.
Chapter One
Getting Familiar with the Foundations of C#

This chapter will provide the reader with an overall review of the most important concepts in C
sharp. This is necessary because the upcoming chapters will build upon the things we review
here. This allows the readers to become familiar with the idioms commonly used in advanced C
sharp programming (which will be quite frequently used in the upcoming chapters). In this way,
this chapter hopes to get the readers on the same page before we move on with advanced
programming techniques and projects in the latter half of this book.
However, if you already have experience with object-oriented programming languages like Java,
Javascript, C++, PHP, Visual Basic .NET, etc., you might think this chapter will probably not be
worth your time, but this chapter will prove to be a really useful checkpoint where you can
review the concepts you are already familiar with. On the other hand, most readers picking up
this book will find this chapter to disclose certain aspects of not only C sharp but also .’NET’
programming that they were previously unaware of.
In short, the content here will provide the readers with foundations necessary for understanding
the discussion of C sharp programming to create advanced applications throughout the course of
this book.

The Essentials of an Object-Oriented Programming Language


There is a set of fundamental elements that form the core of the language itself in any object-
oriented programming language. These elements are generally known as the object-oriented
basics, but this title is quite misleading as these “basics” are not to be underestimated. To be
more precise, these basics are wrapped around with an external shell that gives the object-
oriented language its unique identity. This is why C sharp, even though it is an object-oriented
language like C++, Visual Basic, and Java, has its own unique way of distinguishing itself from
its family members.
In any object-oriented programming language, the underlying functioning principles remain the
same. These principles are essentially the “basics” of an object-oriented programming language,
and they are a total of four. These basic principles are the following:
1. Encapsulation
2. Inheritance
3. Aggregation
4. Polymorphism

As such, any programming language that incorporates these principles is categorized as an


object-oriented programming language. In order to implement each of these principal elements
properly within their cores, programming languages use tools known as ‘idioms ’ and
‘constructors .’ For instance, these include
Templates
Operator overloading
Interfaces
Multithreading
Multiple Inheritance
Exception handling
Pointers
Garbage collection, etc.

When exploring C sharp, we find out that the core of this object-oriented programming language
implements the principal elements with operator overloading, inheritance, interfaces, exception
handling, garbage collection, multiple interface inheritance, reflection, and multi-threading, but
you might notice that C sharp shuns a few functionalities such as templates, raw pointers, and
even multiple class inheritance. The reason why these functionalities were not included within
the C sharp programming language is because of the argument, which, on one side, supports the
claim that these features introduce more problems than they can potentially solve. On the other
side, the belief is that these are key components of any object-oriented programming language,
and the features they bring to the table are priceless, and they need to be included, but keep
things simple and straightforward, further complications were avoided by simply not adding
these features to C sharp.
However, this does not give much confidence to anybody who has any experience in
programming. This is because the feature set of templates, multiple inheritances, and pointers
greatly facilitates the user in Web application and Web Services projects. Hence, this might be a
monumental deal-breaker for some people, but C sharp does not disappoint their end-users. In
order to make up for the lack of such tools, C sharp includes its own feature set that can help
users to build Web Applications and Web Services. For instance, C sharp features a tool that
allows for hosting applications on the Windows platform, namely, ‘COM interop .’ Not only
that, but C sharp also boasts multilanguage programming as well as rapid application
development.
But through all this ramble, there is still good news. As we discussed before, all the object-
oriented programming languages have the same core principles with a difference in the features
implementing them. You will find that some features from other OOPLs carry on to C sharp. For
instance, if you are comfortable with the syntax of C++ or Java, then you’ll find that the syntax
of C sharp is strikingly familiar, thus allowing you to settle in considerably faster. This is just
one of the many similarities you’ll find in C sharp when comparing it to other object-oriented
programming languages, so it’s a good idea to make a quick comparison if you’re coming from
such languages.
In the upcoming sections, we will discuss the object-oriented basics and discuss the relative
features available in C sharp.
Defining Classes
Creating and defining classes is done the same way as you would in C++, albeit the underlying
construct of this action is slightly different in C sharp. The following syntax demonstrates the
construct required to define a class in C sharp.
Access-modifier class name
{
}
One thing to be mindful of is that just like C++, C sharp is a case-sensitive programming
language. Thus, you need to be vigilant of the case in which your classes have been defined
when referencing them. Otherwise, the compiler will not recognize which class you are referring
to.
The syntax demonstrated above has the potential of being confusing, so let’s clarify its elements.
The syntax has two elements - the ‘access modifier ’ and the ‘name .’ The second element is
self-explanatory, i.e., it is the set of characters by which the class is recognized, but the first
element's purpose is to define the scope of the class (you should already be familiar with
‘scopes’). Generally, classes are specified as ‘public ’ (which is the same as ‘global ’ in other
programming languages) so that they can be accessed by any function in any program, as long as
the header file is included (where the classes have been already defined).
So, if we replace the appropriate arguments in the syntax shown above, we will end up with
something like this:
public class MyFirstClass
{
}
In the curly brackets, you fit in your class's contents (the functions, methods, and objects it
includes). If you look a bit closer, you will see that the class's name has all the first letters of each
word capitalized. This is not random or a mistake. Instead, we follow a convention here when
naming classes. The purpose of a convention is to maintain consistency when programming,
which can be really impactful in the long run, but it is not mandatory to follow this naming
convention (known as ‘Pascal Casing’). It’s all up to you whether you choose to use it or not (the
same goes for other numerous conventions in programming).
Using a Class in a Console Application
Assuming that you have some knowledge of programming or any amount of programming
experience, then you must be familiar with the term ‘console.’ When you are using IDE software
to code, you will find a small window in the bottom that looks similar to that of a command
prompt, giving the user feedback information when they execute certain commands (such as
compile, debug, etc.). Moreover, a console will also display syntax errors in the code when asked
to compile the project you have opened currently.
Similarly, suppose we want to work with C sharp to code applications, etc. In that case, we will
do so by using an Integrated Development Environment (such as Microsoft Visual Studio), but
we are not to confuse a ‘console’ with a ‘console application.’ While a console is natively open
in an IDE at all times, a ‘console application’ on the other hand, is simply an executable file that
does not have a fancy GUI. The interface through which the user interacts with the application is
like a simple command prompt.
In such tasks, the most common action that you will likely perform during C sharp programming
is implementing the classes you have defined in a certain console application. We can easily
create a fresh console application by opening a ‘New Project’ within the IDE. The underlying
code for the newly created console application is as follows:
using System;
namespace HelloWorld
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start the application here
//
}
}
}
Now let’s break this code down a bit. At the very start of this code block, we notice a statement
being used, which is ‘using .’ The argument passed to this statement is ‘System .’ In this block
of code, ‘System’ actually refers to a .’dll ’ assembly file available through the .’NET
Framework ’ installed on our computer (using Windows, obviously). We do not need to go into
the details as to ‘why’ a fresh console application is using the ‘System.dll ’ assembly file. A
simple answer to this question of ‘why’ is that this file contains the necessary elements required
for ‘Common Language Runtime.’ It wouldn't be wrong if we even said that the .’dll’ file is the
console application itself. The ‘using ’ statement we use in C sharp is synonymous with the
‘include ’ statement in C++ and the ‘uses ’ statement in Delphi.
In the next step, we specify the ‘name ’ of the console application through the ‘namespace ’
statement. The argument passed to this statement will be the name we assign the project, which
in this case, would be the conventional name of the very first program created by a user, i.e.,
‘Hello World.’ However, in the argument, we do not add spaces in between a single namespace.
The ‘slash’ symbols that you see in the middle of this block of code represent comments.
Anything that is written after three/two slashes (\\\ or \\) is considered as additional commentary
made by the programmer. Comments can be really helpful either when you need to go through
the program's code later on its life cycle or if somebody else is exploring it.
After the initial three comments, we will see the very first class is defined. Since this is a code
generated when we create a default console application, the classes' names and constructs are
standard. It is recommended that you name a class you create something that is self-explanatory,
short, and easy to recall (although not every name can have all three of these elements).
Up next, we have the core element of the entire application, the ‘Main() ’ member. If you have
experience with C++, then you will be quite familiar with this member. Main is not a standard
member. In fact, it has a special property that turns it into what we call a ‘static member .’ The
property associated with a ‘static’ member is pretty useful. It allows us to use the method(s)
associated with such a member without having an ‘enclosing class’ to exist. In addition, an
argument known as ‘string[] args ’ tells us that a bunch of strings (in the form of an array) are
passed to the Main static member. These strings are basically the ‘Command Line Arguments’
that you will generally pass during a coding session.
Printing a Statement in a Console Application
Now that we understand the underlying elements of a console application let’s build one to
display a simple phrase, ‘Hello World!.’ To do this, we will simply be filling in the necessary
arguments to the statements shown in the code of a console application.
using System;
namespace HelloWorld
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadLine();
}
}
}
To print out the phrase, we use two basic functions, namely, ‘Console.WriteLine() ’ and
‘Console.ReadLine() .’ We specify the phrase or sentence we want the console application to
display and pass it as an argument to the ‘Console.WriteLine() ’ function. Once this is done, the
‘Console.ReadLine() ’ function then stands by until it receives the carriage return it expects
before it continues with its job. The purpose of the ‘Console.WriteLine() ’ function is the same
as the ‘cout>>’ statement in the C++ programming language.
When analyzing the usage of the methods to print out the phrase “Hello World!”, you might
notice that these methods were used without including an instance of the corresponding ‘Console
object.’ If this were a normal scenario, then you would be absolutely right, but the truth is that
these methods are actually static members present in a class named ‘Console .’ So, if we want to
call upon and use these methods, then we don’t need to create an instance of the corresponding
class’s object.
Performing a ‘Read’ on the Command Prompt
We will now go over the approach through which we can effectively intercept the arguments
specified to the console application. To do this, we simply pass a special argument to the
‘Console.WriteLine() ’ method. This argument is ‘args[0], ’ and you can see it being
implemented in the following block of code:
using System;
namespace HelloWorld
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine(args[0]);
Console.ReadLine();
}
}
}
When we execute this block of code, whenever we pass an argument to the command prompt, it
is intercepted by the console application displayed on the console.
Passing an argument to the command prompt can be done in two ways (there are other ways as
well, but for the sake of simplicity, we will just stick with two).
Execute an assembly through the command prompt and pass a corresponding
argument.
Using the Microsoft Visual Studio IDE to pass arguments to the command prompt.

Let’s get into some details regarding the second method. Using the .’NET Visual Studio’
Integrated Development Environment is not that complex since you must have experience with
other IDEs at this point. In order to use the IDE to pass an argument to the command line, we
need to perform the following actions:
1. Open the Visual Studio IDE and look for the ‘Solution Explorer’ menu inside the
‘View’ tab.
2. Once you are inside the ‘Solution Explorer’ menu, you will find a list of all the
projects that you have been working on or placed in the IDE’s browsing directory.
Over here, you need to find the project you want to work on for this task and then
just right-click it. This will open a drop-down menu, and from here, you select the
‘Properties’ option.
3. This will open a new window as shown below:

On the left-hand side, you will see a small file navigation interface. From here, double click
‘Configuration Properties,’ and inside, select ‘Debugging.’
4. In the 3rd category named ‘Start options,’ the first section will be ‘Command Line
Arguments.’ Over here, you need to specify an appropriate value. In this case, we
pass an argument ‘Debugging C#.’
5. Once we are done with passing a command-line argument, we can reboot the
application we have opened in the IDE manually or by pressing the ‘F5 key’ as the
shortcut key. Once the application runs using the IDE after a reboot, we will be
able to see the argument passed to the command prompt.
Using Fields and Properties
‘Fields’ and ‘Properties’ are elements that are interestingly related to each other, but before we
can discuss them, let’s first understand the underlying concept of ‘consumers’ and ‘producers’ in
programming. ‘Consumers ’ are those people that are the end-users of things like classes.
Similarly, ‘Producers ’ are those people that build these classes. An interesting thing to note
here that both a consumer and a producer are programmers.
Now with that clarified, let’s talk about ‘Fields .’ A ‘Field’ is simply a bunch of data that is
contained within a class. Conventionally, the fields of a class are never public. Instead, they are
set to ‘private’ by the producer, but there are times when consumers need access to the fields of a
class they are using, but, since the fields are private, they are hindered. This is where ‘Properties
’ come in. Properties have the nature of duality. To elaborate, if a consumer is using this
‘Property Method,’ it will be indistinguishable as if the consumer were dealing with data. On the
other hand, if the producer uses the same property method, it will function as if it were a method.
You might ask why you would even need access to the data fields of a class in the first place.
Well, the answer to that is very simple and straightforward, having access to the data of a class
allows the programmer to have the freedom to make changes to the class’s methods and even
perform some tweaks to the class's objects. Similarly, using ‘Properties ’ allows us to control
how the data in the class is accessed.
Defining a Field
The nature of a field, i.e., the type of data it contains, can generally be anything (it just needs to
conform to the purpose of the class in which it will be used). Since this data is important to the
class, it is generally kept private through the use of access modifiers (i.e., setting its scope to
‘private’). In this way, only the programmer who created the field (the producer) will be able to
make changes to it. If anyone other than the producer wants to access the fields in a class and
make changes to it, they will have to do so through ‘Property Methods.’
In the following block of code, we are creating a field that stores string data.
using System;
namespace HelloWorld
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
private static string arg0 = null;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
arg0 = args[0];
Console.WriteLine(arg0);
Console.ReadLine();
}
}
}
In this demonstration, you can find that we are not using an instance of ‘Class1 ’ in this program.
Now let’s modify this block of code a bit such that we actually use an instance of the
corresponding class while it essentially performs the same job.
using System;
namespace HelloWorld
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
private string arg0 = null;
public void WriteCommandLine( string arg )
{
Console.WriteLine(arg);
Console.ReadLine();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Class1 = new Class1();
class1.arg0 = args[0];
class1.WriteCommandLine(class1.arg0);
}
}
}
Basically, the revision involves how we use the ‘Main()’ method. Originally, this method
handled the majority of the work to perform the corresponding job, but we changed the purpose
of the ‘Main()’ method in the revision such that it’s the only job would be to act as a ‘startup
method’ only. To account for the changes in the way the code works, we implement an instance
of ‘Class1 .’
Defining Properties
Due to their nature and function, ‘Properties’ are basically considered as ‘methods’ (you might
have guessed it when we talked about ‘Property Methods’ in the previous sections). Generally,
properties can be used in one of two ways, either as a ‘right-hand side value ’ or as a ‘left-
hand-side value .’ If the property is being used as an RHS value, we call a specific property
method known as ‘getter .’ On the other hand, if the property is being used as an LHS value,
then the corresponding property method we call is known as a ‘setter .’
Properties also have access to modifiers defining their scope. Conventionally, properties are set
to public. Here’s how a property would be defined:
Access-Modifier Type Property-Name
{
get
{
return field;
}
set
{
field = value;
}
}
In essence, the property has three basic elements - an access modifier (which is generally set to
public), a ‘type,’ and last but not least, a name.
‘Properties’ can be of three types based on their use and implementation, i.e., ‘Read-only
Properties,’ ‘Indexed Properties’ and ‘Write-only Properties.’ Before moving on, let’s discuss
these different types of properties.

Read-Only Properties
The main element through which we can distinguish a read-only property is from observing if it
possesses a ‘getter’ or a ‘setter.’ If the property only has a ‘getter’ then it is a ‘Read-only
Property.’ Just like the name suggests, such properties only allow the users to view the property
elements, such as its values, and the user has no authorization to make any changes.
Here’s an example where we access the value of a ‘Read-only Property’ for the temperature
defined in a class. This temperature class features readings in both Celsius and Fahrenheit scale.
Here’s how we can use the Read-only Property to fetch the scale in which the corresponding
class's temperature will be displayed.
public enum TemperatureMode
{
Fahrenheit, celsius
}
class Temperature
{
private TemperatureMode mode = TemperatureMode.fahrenheit;
private double celsius = 0;
private double fahrenheit = 0;
public Temperature( double aTemperature, TemperatureMode aMode )
{
mode = aMode;
SetTemperature(aTemperature, aMode);
}
private void SetTemperature(double aTemperature, TemperatureMode aMode)
{
if( aMode == TemperatureMode.fahrenheit )
{
fahrenheit = aTemperature;
celsius = FahrenheitToCelsius(aTemperature);
}
else
{
celsius = aTemperature;
fahrenheit = CelsiusToFahrenheit(aTemperature);
}
}
public static double CelsiusToFahrenheit(double celsius)
{
return celsius * (9.0/5) + 32;
}
public static double FahrenheitToCelsius(double fahrenheit)
{
return (fahrenheit - 32) * 5.0/9;
}
public TemperatureMode Mode
{
get
{
return mode;
}
set
{
mode = value;
}
}
public double Value
{
get
{
return mode == TemperatureMode.fahrenheit ?
fahrenheit : celsius;
}
}
public bool Test()
{
return fahrenheit == CelsiusToFahrenheit(celsius)
&& celsius == FahrenheitToCelsius(fahrenheit);
}
}
To determine the scale on which the temperature will be converted to (in simpler terms,
determining whether to use the Celsius scale or the Fahrenheit scale), the block of code shown
above executes a corresponding enumeration.

Write-Only Properties
Just as a property with only ‘getters’ is the defining feature of a ‘Read-only Property,’ a property
that only has ‘setters ’ is primarily known as a ‘Write-only Property .’ In such a type of
property, a user accessing the class can make changes to it and even to the property itself.
Usually, you won’t come across write-only properties as much because they are not often used,
as it can cause unnecessary complications due to the modification privileges given to the end-
user.
However, this does not mean that write-only properties are entirely useless. For example, you
can use the functionality of write-only properties for tasks such as requesting authentication from
the user in the form of a passcode. Instead of using a read-only property to display the
authentication code to the end-user, it would be better to use a write-only property and allow the
user to type the correct passcode in by themselves.
Indexed Properties
This type of property is also simple, like the other two. Just as the name ‘Index’ suggests, this
type of property is primarily used to communicate the items which have been placed in the
corresponding class in the form of a ‘list.’ Since the main user will be a consumer, the form in
which the requested data is displayed is in the form of ‘object[index] .’
Here’s a demonstration of the use of ‘Indexed Properties.’
class IndexedProperty
{
private string[] args = null;
public IndexedProperty(string[] args)
{
this.args = new string[args.Length];
args.CopyTo(this.args, 0);
}
[System.Runtime.CompilerServices.IndexerName("Command")]
public string this [int index]
{
get
{
return args[index];
}
set
{
args[index] = value;
}
}
}
Using an Instance of a Class
In order to create an instance of an object and then have it run in the program where it was
created, we need to call upon a ‘Constructor’ with the help of an operator. When we create an
instance of an object, we can take a bunch of variables and link them to the instantiated object,
but there’s a condition to perform this action: whenever we try to assign a variable to an object,
both elements need to be compatible with one another. The instantiated object’s type and the
variable’s type need to be similar, to be more precise. This linking process will fail if the types of
the object and the variable do not match. The type compatibility even extends to the object’s
predecessors. By predecessors, we mean those objects whose features this object instance
inherited. So, if the variable’s type matches any of the object’s ancestors, then it can be assigned
to the object. In other words, if we have a variable that was previously declared to be of the same
type as an object’s ancestor, then we can use this variable with the very same object’s child
instance as well.
If we want to create an instance of an object, we will need to use a ‘Constructor.’ A constructor
is basically a method that is primarily used during the process of creating an object (this includes
creating an instance as well). A constructor has three elements, a name, an access modifier, and
parameters. The name of the constructor is usually the name of the class to which it belongs to.
The access modifier can be either public or private, and it can have numerous parameters or
none.
The following example shows the process of creating an object instance with the help of a
constructor.
// simple object creation
FileStream fs = new FileStream("c:\\temp\\killme.txt", FileMode.CreateNew);
fs.Write(new Byte[]{65, 66, 67, 68, 69}, 0, 5);
fs.Close();
// array examples
string[] strings = new string[10];
strings[0] = "Some Text!";
int[] integers = new int[]{0,1,2,3,4,5};
Defining an Interface
In the context of object-oriented programming languages, an interface isn’t any different from
what you might actually be familiar with. The main use of the interface is to create a method of
interaction for a specific class. To be more precise, an interface is an actualization of tapping into
the functionality of a class. Consider a sound system installed in a vehicle. This sound system
has two circular controllers that can be rotated to navigate through the menu, increase or
decrease the volume, change the radio station, or even shuffle through songs being played
through external media. Now, let’s narrow things down a bit. Let’s say that these hardware
controllers allow you to tune the radio station, and you can also do this without having to use
these knobs as well. For instance, you can have a small infrared controller that can do this task
for you. In this scenario, the tuning of the radio stations is done through an underlying interface,
and we can access the functionality of this interface through external tools. If you think about it,
the sound system's volume is controlled through a specific ‘volume interface.’ We can connect to
this interface to leverage its volume changing functionality through an infrared remote, hardware
buttons, or even voice control. As such, the hardware buttons controlling the volume are seen as
the ‘physical controls.’ The aspect we are controlling is ‘volume,’ which is known as the
‘attribute.’ We manipulate this ‘attribute’ by implementing either ‘Methods’ or ‘Property
Methods’, and these methods act as the supporting framework of an interface.
Here’s how you can easily define an interface.
public interface IAudio
{
void AdjustVolume( int value );
}
Implementing an Interface
Once we have created an interface, we still need to implement it properly in a program or
application. Generally, interfaces are implemented within classes. When implementing an
interface, it should always be remembered that all the interface methods will be implemented as
well.
To implement an interface, simply specify the class you want it to be in. The following block of
code shows us how we can implement an interface within a class:
public interface IAudio
{
void AdjustVolume(int value );
}
public class Radio : IAudio
{
private int volume = 0;
void IAudio.AdjustVolume(int value)
{
volume += value;
}
}
In this code, the interface we are implementing is ‘IAudio, ’ and the class in which we are
implementing it is ‘Radio .’ The process is simple. First, we write the access modifier of the
concerned class, then type its name, then place a colon after the class’s name (:) and finally,
specify the interface's name. This has been demonstrated in the 3rd line of the code block.
Inheritance
The concept of inheritance is almost universal, be it in biology or computers. Inheritance is
basically when a class passes on its features and certain characteristics to another class, but the
result is not going to be a completely identical copy of the original class. The inheritance
relationship usually involves two or more than two classes. The class whose features are being
inherited is known as the ‘superclass, ’ and the class which is inheriting those features is known
as the ‘subclass .’ Think of it as the relationship of a parent and a child, in this case, the first one
(superclass) would be the parent class and the second one (subclass) would be the child class.
Like we discussed before, we are not simply making an identical copy of the original class.
Instead, the subclass has its own unique features, and it simply inherits the corresponding fields,
properties, and methods belonging to the original superclass.
However, to make the inheritance work, we must also know how to denote it in our code
properly. Let’s say that we are dealing with two classes, ‘Class X’ and ‘Class Y.’ If we say that
class Y inherits the members of class X , then we would denote this inheritance relationship in
the following syntax.
Public class B : A
Here is a list of some important inheritance concepts that you always need to remember.
The class from which the features are inherited is the parent class, and the class
which inherits those said features is the child class. For example, If ‘Class Y ’
inherits the members of ‘Class X,’ then ‘X ’ is the Parent and ‘Y ’ is the Child.
If class Y inherits the members of class X , then class X is referred to as the
‘superclass, ’ and class Y is referred to as the ‘subclass .’
The process of ‘Inheritance ’ is sometimes also referred to as ‘generalizing .’
If the inheritance relationship has multiple children, then the relationship of each
child with each other would be termed as ‘siblings .’ So, multiple classes that
inherit their members from the same superclass are termed as ‘siblings .’

Here’s an example of using the Inheritance feature, where multiple classes are inheriting the
members of the ‘Radio Class ’, which, in this case, would be known as the parent class.
public interface IAudio
{
void AdjustVolume(int value );
}
public class Radio : IAudio
{
private int volume = 0;
void IAudio.AdjustVolume(int value)
{
volume += value;
}
public int Volume
{
get
{
return volume;
}
set
{
volume = value;
}
}
private double station = 94.1;
public double Station
{
get
{
return station;
}
set
{
station = value;
}
}
public void Receive()
{
}
}
public enum RadioBand
{
AM, FM
}
public class AMFMRadio : Radio
{
private int volume = 0;
void IAudio.AdjustVolume(int value)
{
volume += value;
}
public int Volume
{
get
{
return volume;
}
set
{
volume = value;
}
}
private double station = 94.1;
public double Station
{
get
{
return station;
}
set
{
station = value;
}
}
public void Receive()
{
}
}
public enum RadioBand
{
AM, FM
}
public class AMFMRadio : Radio
{
This might be a little confusing for you because there are multiple instances of inheritance going
on, but the core concept remains the same. In this example, we have a parent class (superclass),
‘Radio ,’ and two child classes (subclasses), ‘CommunicationsRadio ’ and ‘AMFMRadio .’
These sibling classes inherit the important members of their parent class in order to perform their
own unique functions. For the ‘CommunicationsRadio ’ class, it would be to enable the
functionality of transmitting and receiving radio signals, and for the ‘AMFMRadio ’ class, it
would be to support different Radio Bands, i.e., Amplitude Modular Bands (AM) and Frequency
Modular Bands (FM).
Encapsulation and Aggregation
Both ‘Encapsulation’ and ‘Aggregation’ indicate the affinity of a class (or any data structure) to
be stuffed with members, but both these terms are not the same. While encapsulation refers to the
affinity of a class to withhold members within itself, aggregation includes those members that
are classes themselves (or data structures). If the concept of encapsulation is still confusing, then
consider an analogy. Think of the small leaflet that has small compartments holding medicine
tablets. The medicine is ‘encapsulated’ in the leaflet. In this analogy, the ‘medicine’ is actually
the ‘class,’ which has the methods, functions, and objects, and the leaflet represents the
‘encapsulation’ method. Through the use of encapsulation and aggregation, we can essentially
put data in a class while controlling the authorization to access it. With encapsulation, we can
add simple data types and structures. With aggregation, we can add more complex data types and
structures inside a class.
However, we cannot just throw data randomly inside classes. We need to think about which class
is the best container for our data. One way of going about this is to look through the list of
classes available to you and determine which is the most suitable contender, i.e., which class is
inherently responsible for holding a specific type of data. For example, if we consider the human
lungs as ‘data,’ then it would make more sense to put them inside a ‘human body (class)’ rather
than in a plant (another class).
Let’s use the ‘Radio ’ class to explore how we can implement ‘Encapsulation’ and
‘Aggregation.’
public class BoomBox
{
private AMFMRadio radio;
public AMFMRadio Radio
{
get
{
return radio;
}
}
BoomBox()
{
radio = new AMFMRadio();
}
}
In this code block, we are working with a new class that we haven’t previously used called
‘BoomBox .’ The interesting part is that this class actually contains the ‘AMFMRadio ’ class.
As such, the ‘AMFMRadio’ class is representing the process of encapsulation as well as
aggregation.
Polymorphism
The concept of ‘Polymorphism’ in C sharp is actually not that complicated. Polymorphism is
basically involved when a programmer encounters a problem that can be handled by any general
‘provider.’ However, the catch here is that the provider must be part of a bigger set of providers.
This means that our problem can be solved regardless of whichever provider we choose from this
collection. This is known as ‘Polymorphism, but just understanding polymorphism from this
perspective might not do you any good so let’s take a more technical approach.
First, let’s take a class and declare it as a general type. When we generalize a class, it basically
inherits the type of its parent class (the superclass). If we want to take this class and create
several instances and want each instance of the class to have a type, we specify and not a general
type, this is our ‘problem.’ The notion of this being a ‘problem’ might seem silly, but it's to help
you understand the concept of ‘polymorphism.’ We can solve this problem by choosing a type
from a selection of different ‘types.’ Choosing any one type will solve the problem, but we still
have a wide selection we can choose from. This is ‘polymorphism’ where we first declare a class
of a ‘general type’ and then declare instances with specific ‘types.’ This phenomenon can be
easily observed in the working of the ‘EventHandler delegate .’ The delegate is instructed in a
way such that its initial parameter will be an object. Since this is the first parameter, the class
harboring the object will be considered as a ‘root’ for all the upcoming classes that will be used.
So, this means that the delegate can virtually take any object as the first parameter to satisfy the
need to specify a root class.
Access, Class, and Member Modifiers
Let’s first talk about ‘Access Modifiers .’ To put it simply, access modifiers define what the
users of a class can see and access. If the access modifier of a class is set to ‘private ,’ then the
consumer will not be able even to see the class, much less try to access it. If the access modifier
is set to ‘public ,’ then the consumer will be able to see the class as well as access its contents
and make changes to it.
The practical use of access modifiers is allowing for guiding a user during their programming
session. If someone is using your class in their code, then keeping those classes ‘private’ that do
not require any attention from the consumer will focus the concentration primarily on the classes
that have been purposefully kept ‘public’ by the producer. In this way, the producer ensures that
the consumer only tinkers with those classes that need interaction in order to use them.
In C sharp, there are a total of five access modifiers that you can use. These access modifiers
have been listed below, accompanied by brief explanations.
1. Public Access Modifier : this modifier provides the end-user with the freedom to
access the members of the corresponding class (this also includes the ‘types’ in the
class as well).
2. Protected Access Modifier : this access modifier is generally used with classes
that are nested (a class within a class). As such, the subclasses (child classes) will
be able to access the members of the superclass (parent class) and other classes
within the nest, but the same level of access is not given to consumers. Instead,
they will be restricted from accessing the members of the nested classes.
3. Private Access Modifier : any members of a class that have a private access
modifier cannot be accessed by any subclass (child class) or any other user except
for the one who created the class.
4. Internal Access Modifier : a class whose members and types have their access
modifier specified to ‘internal ’ have their access restricted only to the assembly
in which they are present. In this way, any external will not be able to access these
classes, or members and the code will be able to communicate with the members
and types of classes.
5. Protected Internal Modifier : this access modifier is basically the result of
slapping the protected modifier on top of the internal modifier. Just as how a
protected access modifier would generally be used in nested classes, the protected
internal modifier is mostly used with nested types as well. Only the assembly has
unrestricted access to the members of the nested classes in a protected internal
modifier.

However, there are some rules you need to follow when using access modifiers in order to avoid
generating errors.
Whenever you are defining a high-tier type, its access modifier must always be
specified to ‘Public.’ Otherwise, it will surely cause complications when other
types need to communicate with the high-tier type. If you do not want to use the
‘Public’ access modifier, then the only other option you have is to use the
‘Internal’ access modifier.
Whenever you are dealing with nested classes or types (in a nested class, a class
contains another class. Similarly, a nested type is a type that holds the definition of
another type), you have to choose between either using the ‘Private’ access
modifier or the ‘Protected’ access modifier.
Even though ‘Protected Internal’ is a combination of two access modifiers
(protected and internal), it is highly advised to avoid combining any other access
modifiers in this way.
If a class or a type is not specified with any access modifier, then a ‘default access
authorization’ will be given to the corresponding members, but it is not
recommended to rely on this. Producers should always specify the appropriate
access modifier.

The concept of using modifiers with Classes and Members has already been discussed in one
way or the other when we talked about access modifiers. Regardless, if you find that the class
you have defined is enclosed within a namespace, it is best to set its access modifier to either
‘Public’ or ‘Internal.’ When working with nested classes, your options are limited as to which
access modifiers you can use to define them. These options include ‘protected, protected
internal or private’ access modifiers.
Members give the producer the freedom of assigning any access modifier to them. If you do not
specify any access modifier, then it will be set to private by default.

Reflection
This is basically a functionality that is largely used in the .’NET Framework .’ By using
‘reflection,’ a user can explore a program’s assembly to extract data in the code, which can
include.
Namespaces
Interfaces
Classes
Methods
Properties
Fields

Apart from that, reflection is an extremely useful object-oriented function that allows users to:
Execute ‘IL ’ (Intermediate Language) code during a program’s run-time.
Use special methods that allow for the viewing of metadata values recorded in
attributes.

Do some detective work, for instance, exploring the types defined in the corresponding assembly
and uncovering the members.
Chapter Two
Working with the Assembly
Viewer and UserControls

In the very last section of the previous chapter, we briefly discussed the object-oriented function
‘Reflection.’ This chapter extends the discussion and allows the reader to explore the practical
use of ‘Reflection’ to examine the data contained within the assemblies.
This entire chapter's core concept is based on dynamically loading the assemblies and using
Reflection to explore this assembly using the assembly viewer. The main take away here is that
understanding the process of loading assemblies and using them gives huge potential beneficial
uses. For instance, we can wirelessly load assemblies using HTTP connections, and by lightly
programming the client, we can automate two tasks:

Deploying applications that are based on the ‘Windows-Forms’ framework.


Roll out updates for these applications based on Windows Forms.

Aside from this, we will also explore a number of other topics in this chapter, such as creating
and declaring static methods, using interfaces like IEnumerator, and practically demonstrating
the use of inheritance.
In the end, we will also explore the functionality of UserControls to create the buttons, icons,
and actions that you see designed in many Windows applications.

Analyzing the Assembly Manager’s Code Listing


In this section, we will explore one of the most important modules necessary for using the
Reflection function to load assemblies and extract information. The necessary functions,
methods, classes, and objects can be found within the ‘AssemblyManager.cs ’ module.
Unfortunately, the website on which this module's source code was hosted has been shut down,
but the following list shown below has all the important bits and pieces you would need from the
module itself (such as the methods or classes).
1: using System;
2: using System.Reflection;
3: using System.Diagnostics;
4: using Diag = System.Diagnostics;
5: using System.IO;
6: using System.Collections;
7: using System.Text;
8: using System.Windows.Forms;
9:
10: namespace AssemblyViewer
11: {
12: /// <summary>
13: /// Summary description for AssemblyManager.
14: /// </summary>
15: public class AssemblyManager
16: {
17: private string name = "";
18: private Assembly;
19:
20: public AssemblyManager(string assemblyName)
21: {
22: Debug.Assert(File.Exists(assemblyName));
23: Name = assemblyName;
24: }
25:
26: public Assembly Assembly
27: {
28: get
29: {
30: return assembly;
31: }
32: }
33:
34: public string Name
35: {
36: get
37: {
38: return name;
39: }
40: set
41: {
42: if(name.Equals(value)) return;
43: name = value;
44: Changed();
45: }
46: }
47:
48: private void Changed()
49: {
50: Debug.Assert(File.Exists(name));
51: assembly = null;
52: assembly = Assembly.LoadFrom(name);
53: }
54:
55: private string Formatted(Type type)
56: {
57: const string mask = "{0} \r\n";
58: string result = string.Format(mask, type.Name);
59: Broadcaster.Broadcast(result);
60: return result;
61: }
62:
63: private string Formatted(MemberInfo info)
64: {
65: const string mask = "\t{0} {1}\r\n";
66: string result = string.Format( mask,
67: info.MemberType.ToString(), info.Name );
68: Broadcaster.Broadcast(result);
69: return result;
70: }
71:
72: private string Load()
73: {
74: StringBuilder str = new StringBuilder();
75: IEnumerator outer = assembly.GetTypes().GetEnumerator();
76:
77: while(outer.MoveNext())
78: {
79: Type type = (Type)outer.Current;
80: str.Append(Formatted(type));
81:
82: IEnumerator inner = type.GetMembers().GetEnumerator();
83:
84: while(inner.MoveNext())
85: {
86: str.Append(Formatted((MemberInfo)inner.Current));
87: Application.DoEvents();
88: }
89: }
90:
91: return str.ToString();
92: }
93:
94: public string Text
95: {
96: get
97: {
98: return GetText();
99: }
100: }
101:
102: public string GetText()
103: {
104: return Load();
105: }
106:
107: }
108:}
The ‘using’ Statement
Generally, ‘using ’ is implemented in either of the two scenarios (or in both at the same time):
When importing a namespace
When handling objects (in this case, it would be used as a ‘block statement’)

In the extensive list shown above, implementing the ‘using ’ statement has already been
demonstrated. If you have any experience with C++, then you can think of the ‘using ’ statement
as the ‘include ’ statement. If C# is your first object-oriented programming language exposure, it
will help you understand the purpose of the ‘using ’ statement as a tool that helps you bring in
external references to your assembly, but take note that it will be stored within a file with the
extension .’DLL’ whenever you are working with an assembly. So, if we use the ‘using ’
statement to add an assembly itself, we are essentially bringing in a .’DLL’ file. Moreover, this
statement can also be used to point to specific classes or functions that belong in a general
assembly file. If we want to use ‘Reflection,’ we will have to refer to the appropriate assembly
file.
using System``.Reflection;
The assembly we are referring to is ‘System.dll, ’ and the class we are using ‘System.Reflection
’ is part of the assembly file.
If we want to use the controls to access the Windows Forms functionalities, then we will have to
include the corresponding assembly file (System.Windows.Forms ) in the program first.
We can also implement the ‘using ’ statement to create a reference for a namespace. Whenever
we specify this ‘reference,’ the code will automatically interpret it as the namespace it is linked
to. For example,
using System.Diagnostics;
to
using Diag = System.Diagnostics;
Whenever we use the term ‘Diag ,’ the program will see it as the ‘System.Diagnostics ’
namespace.
Before moving on to the next section, we will discuss one final use of this directive. Let’s say
that you are implementing the ‘using ’ statement to create a block using an object you have
specified. If the ‘using ’ directive is implemented explicitly with the object that the block will be
using, then once this block ends, the object will be thrown away by the program. This will
continue to happen regardless if there is an exception before the block finishes executing. Here’s
a demonstration.
using (FormAbout form = new FormAbout())
{
form.ShowDialog();
}
Once this simple code block finishes executing, the object will be thrown away.
Working with the Assembly Using Reflection
The main element which is arguably the one that does most of the work for the entire
‘AssemblyManager ’ class is none other than the function ‘Load() .’ This function primarily
utilizes specialized objects, known as enumerators, to perform two tasks (using a different
enumerator for each one):
Going through every type which has been specified in the assembly and loads
them.
Going through the corresponding members of each type previously explored and
then loading these members.

By creating specialized looping structures in a program (for instance, a nested loop), we can
effectively iterate over all of these types and their respective members, thus extracting this
information. Once the function has gathered the necessary information, it then converts it into a
tangible form, like a string, and then displays it to the user. This gives the end-user a much-
needed insight for designing and creating elements such as an interface for a class.
Before we move on, let’s briefly discuss enumerators. Consider that you are presented with data
stored in the form of a list or an array, and you are asked to design a program that will go
through each entry in the data structure and perform a certain task. Traditionally, the first
approach that you might consider is to create a loop for such a task. To do this, you would create
statements using either ‘for ’ or ‘while .’ However, we know that the construct of such a
directive is essentially a ‘statement .’ If we want to use a method to execute a certain task when
the program is iterating over the data, we will need to pass certain parameters to the
corresponding method, but methods do not accept statements as their parameters. This is where
‘enumerators ’ come in. Enumerators are simply objects that can be used for special tasks such
as looping through a table of data, an array, a collection of strings, etc. Basically, enumerators
are used along with an algorithm. So, you take an enumerator, pass it to a method as its
parameter, and specify the algorithm the method will use.
If you want to use the ‘Load() ’ function, you will first have to know about its syntax and define
it in your program. If you look at the Assembly Manager’s code listing at the beginning of this
section, you will find the load function's definition beginning from ‘line 69 to line 90 .’ If we
bring our attention to line number 70 on the code listing, we will find that the function definition
includes creating an object instance named ‘StringBuilder .’ An instance of this object is created
seemingly effortlessly because it has already been defined previously (you will find the
definition if you look through the namespace ‘System.Text ’). The purpose of this object is to
boost the logistics of the converted string characters. To be more precise, a lone string buffer
available to the ‘StringBuilder ’ object has a considerably larger capacity. Thus, a larger volume
of string information can flow through the buffer, making string operations even faster.
Now let’s proceed with discussing how we can actually use Reflection. The first requirement is
to select an appropriate instance of an object from the assembly file we are working with. Once
we have the object instance in our sight, we essentially have the assembly’s reference. From this
point, all we have to do is simply employ Reflection, and the assembly will reveal all the
members that have been defined within it, but things are a bit different if we are dealing with a
type instance instead of an object instance. As we know, the members of each type are specific to
their unique elements (for instance, a type that only has members referring to ‘Methods’ and
other types referring to ‘Field’ information, etc.). So, when we use Reflection on a type instance,
then we will extract information that it refers to. Hence, if we want data regarding Methods,
Fields, Events, Properties, etc. then we will have to use Reflection on the respective type
instances.
Although we know what to do when we have an object instance, however, we do not know how
we can summon the object instance in the first place. Well, there are largely two methods
through which we can extract an object instance.
1. Using a method ‘AssemblyLoadFrom() .’ The argument to be passed to this
method is the name of the assembly we are working on.
2. Using a static method ‘Reflection.Assembly.GetcallingAssembly() .’

With either of these two methods, we can essentially extract the reference to the assembly we
want to work on. Once you obtain the reference, you now need to use appropriate methods to
perform certain actions on this assembly file. For instance, if we have an assembly reference and
want to extract information that tells us all the types defined in this assembly, we will have to use
the appropriate methods. In this case, we will first have to pass an array declaration and set the
‘type’ of this array to the types we want to extract from the assembly. Once the array is set up, all
we have to do is call upon the method ‘assembly .GetTypes() .’ However, you need always to
remember when using this method that the part ‘assembly ’ basically is the actual assembly
reference you previously obtained.
There’s more to the functionality of ‘Reflection ’ than just simply unraveling the contents of an
assembly. When we use Reflection to extract information regarding the types and members
contained within the assembly, at this point, Reflection is capable of using them as well, even
though their definitions are in the assembly file. Here’s a demonstration of how to load an
assembly file and using reflection to execute a static method which is originally from the
assembly itself.
const string s =
"c:\\winnt\\Microsoft.NET\\Framework" +
"\\v1.0.3705\\System.Windows.Forms.dll";
Assembly = Assembly.LoadFrom(s);
Type type = assembly.GetType(
"System.Windows.Forms.MessageBox", true);
type.InvokeMember("Show", BindingFlags.Public |
BindingFlags.InvokeMethod |
BindingFlags.Static, null, null,
new object[] {"Invoked by Reflection"});
The ‘Broadcaster’ Class
If you go through the Assembly Manager’s code listing, you will come across this somewhat
unique statement utilizing a class which most of you would not have seen before.
Broadcaster.Broadcast
This statement essentially uses the ‘Broadcaster’ class to literally ‘broadcast’ information to a
designated target. Any other user who intercepts this broadcast can access the information being
propagated as well. Such an approach is commonly used to send out information such as an
ongoing operation's current progress. For this, the class would essentially need to define a ‘main
form’ as the application that will receive the broadcast and display the information. We can see
the ‘AssemblyViewer ’ use this same approach to display its current status while an operation is
ongoing.
Here are the ‘Broadcaster ’ class and the necessary interface for receiving the broadcast.
1: using System;
2: using System.Collections;
3:
4: namespace AssemblyViewer
5: {
6: /// <summary>
7: /// Summary description for Broadcaster.
8: /// </summary>
9: public class Broadcaster
10: {
11: private static Broadcaster instance = null;
12: private ArrayList listeners = null;
13: protected Broadcaster()
14: {
15: listeners = new ArrayList();
16: }
17:
18: static private Broadcaster Instance
19: {
20: get
21: {
22: if( instance == null )
23: instance = new Broadcaster();
24: return instance;
25: }
26: }
27:
28: public static void Add(IListener listener)
29: {
30: Instance.listeners.Add(listener);
31: }
32:
33: public static void Remove(IListener listener)
34: {
35: Instance.listeners.Remove(listener);
36: }
37:
38: public static void Broadcast(string message)
39: {
40: IEnumerator enumerator = Instance.listeners.GetEnumerator();
41: while(enumerator.MoveNext())
42: {
43: if(((IListener)enumerator.Current).Listening())
44: ((IListener)enumerator.Current).Listen(message);
45: }
46: }
47: }
48:
49: public interface IListener
50: {
51: bool Listening();
52: void Listen(string message);
53: }
54: }
Can essentially link any class with the ‘IListener ’ interface and the class will gain the ability to
intercept the string information that is being sent to the target location, but to do this, the class
needs to implement the interface and register with the class that is ‘Broadcasting .’
Using the ‘Broadcaster’ Class
Now let’s understand how we can effectively implement this class in an application. Before that,
the reader must always remember that ‘Broadcaster ’ belongs to those groups of classes that
would ideally want only one instance of their respective class running. Such a group is known as
‘Singleton .’ So, the broadcaster class isn’t built like other classes. In order for it to function as
the other singleton classes, it has a ‘Private Instance Property .’
In the entire class, you will find that there are numerous public methods available, but we must
keep in mind that every single one of these ‘public methods ’ is, in fact static . Whenever a
public member from the broadcaster class is called, the corresponding method first and foremost
checks with a property named ‘Instance ,’ and this property is set to ‘read-only ,’ so the method
can access it but not modify it. This property then double-checks whether the broadcaster class
has any instances created and if so, then how many are there. So, if the Instance property
confirms that there is no ‘singleton ’ instance of the broadcaster class, then it proceeds to create
one. This newly created instance of the broadcaster class is then passed on to a field (set to
private) whose name is ‘instance .’ If the Instance property confirms that a singleton instance of
the class is already present, it then links the instance to the same private class. Once done, an
object from the singleton instance of the class is given by the Instance property. The end product
of all this skirmish is that the broadcaster class ends up with an object that refers to the
broadcaster class's singleton instance.
Lastly, there are two important elements left,
The IListener Interface - we can add this interface to an array defining the parts
of the system that are tapping into the broadcast. Once the interface is added to the
listener’s ‘ArrayList ,’ we can now execute the broadcast() method. Whenever
we do so, every listener in the array will have the broadcaster information
propagated to it.
The IEnumerator - we use an enumerator as opposed to using a ‘for, while ’ loop
statements to have the method loop through the entire list of listeners defined in
the ‘ArrayList .’

Defining the Interface for the ‘Broadcaster’ Class


As we have already mentioned before, the interface that is primarily being used with the
Broadcaster class is the ‘IListener ’ interface. This interface has two essential methods that
help carry out the core function of the class.
1. Listening : this is a function whose output is a True or False value. In other
words, a ‘Boolean value .’ This Boolean value returned by the function actually
tells the interface if the object (in which the interface was implemented) is willing
to intercept the messages being sent from the broadcaster or not. In this way, the
object can mute the broadcast without having to remove its registry with the
broadcaster it is linked to.
2. Listen : this method is responsible for intercepting the message being broadcasted
in strings.

In order to use the broadcaster in your application, all you have to do is implement the
‘IListener ’ interface with a class that you want to receive the broadcasts. The following block
of code demonstrates how to use the ‘IListener ’ interface in order to use the broadcaster class.
public class FormMain : System.Windows.Forms.Form, IListener
{
private void FormMain_Load(object sender, System.EventArgs e)
{
Broadcaster.Add(this);
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
Broadcaster.Remove(this);
base.Dispose( disposing );
}
void IListener.Listen(string message)
{
ChangeStatus(message.Trim());
}
bool IListener.Listening()
{
return true;
}
}

Working with Windows Forms Control


Numerous Form Controls have been defined in the AssemblyViewer that we can use. For
instance, we have the:
StatusBar, MainMenu, OpenFileDialog, RichTextBox controls, etc.

Only in the ‘FormMain.cs’ module of the AssemblyViewer. We can use these controls to create
interfaces for fully fledged applications using the .NET Framework , but we cannot fully list the
module's entire code since it contains over 400 entries. Due to this, we will see portions of code
shown from this module.
Let’s start things off by simply adding the element of ‘Form Controls’ in an existing project.
Whenever a form is included in a program, the primary namespace used in the project is
essentially extended to cover the class responsible for defining the ‘form ’ as well. As such, we
do not need to create a separate namespace when adding a form control. The syntax for including
a Windows Form Control has been shown below:
public class FormMain : System.Windows.Forms.Form, IListener
Once you begin using Form Controls in your programs, you will come to notice that the
underlying syntax of adding a ‘form control’ is actually based on ‘Inheritance .’ This is because
for each ‘form control’ added to the project, the syntax creates a class that inherits from
‘System.Windows.Forms.Form .’ If we were to explain just the syntax shown above, then it
would essentially say that the class ‘FormMain ’ is supposed to inherit its members and types
from the assembly file ‘System.Windows.Forms.Form .’ Finally, this simple line of code also
implements the ‘IListener ’ interface as well.
If you use the ‘Visual Studio .NET ’ as an IDE for C# programming, then in this case, you will
find great convenience in implementing Windows Forms in a project. This is because with
Visual Studio .NET, you have two options when working with Windows Forms Controls:
1. Code view: just as the name suggests, the IDE shows you the underlying codes
responsible for the shape, size, and contents of the ‘form control.’ You can change
its elements by manipulating the code directly and include additional controls by
adding the corresponding code.
2. Form view: in this option, Visual Studio .NET provides the programmer with a
purely graphical view of form control being added. In this mode, you can
manipulate the form control elements directly by interacting with the IDE
interface. You can also add other form controls through the options provided
within the IDE itself. This provides an intuitive way for people to work with form
controls without having to interact with the corresponding code too much.

Implementing the ‘StatusBar’ Form Control


Anyone with any experience with using computers is familiar with the term ‘Status Bar .’
Generally, the purpose of a status bar is to display the progress of anything, and these status bars
are usually present in an application. For example, take an installation wizard application. When
you click the ‘install ’ button (which is also a form control if you hadn’t noticed), the application
proceeds to copy the application files to the specified destination. The installation progress is
shown on the ‘status bar .’ We can also use ‘StatusBar ’ as a live graphical feed shown the
application’s current status. To implement the ‘StatusBar ’ in an application, we use the present
in the module using the application known as ‘AssemblyViewer .’ The code that you will have
to extract has already been shown below.
private void Initialize()
{
openFileDialog1.InitialDirectory = GetInitialDirectory();
Broadcaster.Add(this);
}
private void ChangeStatus(string status)
{
statusBar1.Text = status;
statusBar1.Refresh();
}
void IListener.Listen(string message)
{
ChangeStatus(message.Trim());
}
We already talked about how we can achieve this functionality using the Broadcast function in
the broadcast class and the corresponding interface ‘IListener .’
Implementing the ‘MainMenu’ Form Control
On any standard windows application, you will see a ‘main menu’ that features all possible
features that a user might want to access. Generally, a menu can be primarily made up of only
menu items or a bunch of button controls too. If we look at a menu from a technical viewpoint, it
will have two objects - ‘MainMenu ’ and ‘MenuItem .’ When we are creating a ‘MainMenu’
form control, we are basically taking a blank form control and placing the respective objects and
elements on it, (although the IDE provides templates for this purpose as well).
The interactive process of adding elements on a ‘MainMenu ’ form control is very intuitive,
easy to understand, and doesn’t require any special coding so let’s move on to the next form.
Implementing the ‘OpenFileDialog’ Form Control
The ‘OpenFileDialog’ form control is something that you have come across when using
Windows. When you are uploading something from your computer’s hard drive to cloud storage,
you first need to specify the location of the file on your system. This opens a small pop-up
window which is like a mini-file explorer, and you navigate to your desired file through this
explorer. This is the ‘OpenFileDialog ’ form control being practically implemented. To
implement this, we simply need to use a method that is defined in the ‘FormMain ’ module as
shown below.
public void OpenAssembly()
{
if( openFileDialog1.ShowDialog() == DialogResult.OK)
OpenAssembly(openFileDialog1.FileName);
}
The statement ‘OpenAssembly ’ is responsible for loading the file we have just selected on to
the AssemblyViewer. Remember that you will have to add corresponding functionality to the
‘OpenFileDialog’ form control for different purposes. For instance, you might remember that
some pop-up file explorers like this have a special category named ‘File Type ’ which allows the
user to filter through different file types. We can add this functionality to this form control as
well by using the following line of code:
openFileDialog1.Filter = "Class Library(*.dll)|*.dll|Executables
(*.exe)|*.exe";

Multi-Threading using the ThreadPool Class


The very subject of ‘multi-threading’ is not a simple one but, almost every programmer or a
computer enthusiast is familiar with what this term insinuates. A thread basically defines a
stream of code execution that is given to an application by the CPU. A CPU has a finite number
of threads that are advertised as part of its specification (for example, 8 core and 16 threads CPU
means each core has features 2 threads).
In order to ensure that an application initializes smoothly and then also runs without being
bottlenecked by aspects such as waiting for a portion of code to finish executing before
proceeding, programmers need to implement multi-threading. We can go on talking about multi-
threading for hundreds of pages and still not cover the entire topic, thus let’s talk about multi-
threading only when we work with AssemblyViewer . Let’s discuss multi-threading inside the
AssemblyViewer application itself. When you run the application, you see a ‘splash-screen’ as
the greeting animation. Well, AssemblyViewer uses a total of 2 threads at this point, one thread
is used to execute the code for the splash-screen while the other thread is used to initialize the
application itself. The splash-screen itself serves other purposes as well, but that’s a discussion
for another day.
In this section, we will talk about the class which is primarily designed to help programmers
implement and handle multi-threading inside their application. This class is the ‘ThreadPool ’
class. Think of this class as a bank manager. Just as how the bank manager ‘manages’ the
employees at the branch, similarly, the threadpool class manages the total number of threads that
are available to the application, but when you are implementing multi-threading on Windows
Form Controls, it calls for extra care because form controls can readily gobble up and hog a
precious resource, threads, for other applications or other processes in the same application.
The following lines of code use the threadpool class to use multi-threading to implement a
different animation of the same splash-screen.
1: bool done = false;
2: private void Increment()
3: {
4: Opacity += .05;
5: lock(this)
6: {
7: done = Opacity >= 1;
8: }
9: }
10:
11: private void Show(Object state)
12: {
13: try
14: {
15: while(!done)
16: {
17: this.Invoke(new MethodInvoker(Increment));
18: Thread.Sleep(100);
19: }
20: Thread.Sleep(1500);
21: }
22: finally
23: {
24: Close();
25: }
26: }
27:
28: public static void Splash()
29: {
30: #if !DEBUG
31: FormSplash form = new FormSplash();
32: form.Opacity = 0;
33: form.Show();
34: ThreadPool.QueueUserWorkItem(
35: new WaitCallback(form.Show));
36: #endif
37: }

Implementing a Control Library


If you want to start building UserControls, the easiest way is to use the template in the Windows
Control Library available in the New Project dialog. Using a solitary UserControl the project will
be made, and an assembly having a DDL extension will be yielded by the Windows Control
Library. There is another way, to begin with, Class Library and later you add all the
UserControls yourself, but this method is not supported as there is no motivation not to use easy
shortcuts if you have easy access to them.
The yield type you get will be a Class Library at the point when a Windows Control Library is
made. The Windows Control Library template will add modules like UserControll.cs and
AssemblyInfo.cs. It will likewise add namespace references like System, System.Drawing,
Systemn.XML, and System.Data. To start working with the first UserControl, a class that is
present in the UserControl module can be used. It is inherited from the UserControl. To add the
metadata, the AssemblyInfo file can be used.
The Windows Control Library allows you to add unlimited UserControls as per your
requirements or demand. In light of the fact that a .resx file is related to the UserControl, it is
preferred to restrict every module to a solitary UserControl, but there is definitely no restriction
to have a solitary class for every module.
You can also build the UserControl by using some general solution and later test it with the help
of some generic application. Many experts mostly recommend this method. It is easy to include
the new UserControl in any application when the requirements like methods, constituent
controls, overall properties, and events are present in the control. In this chapter, this method is
used for building the UserControls. Considering the main control, it consists of a pile of buttons.
These buttons are 4 in total. Based on the UserControl’s size these 4 buttons are consequently
resized. There is another control with the help of which a UserControl is made having two
listboxes. This control also has buttons that allow the component movement between the
listboxes. These buttons serve as visual allegory.

Creating a ButtonCluster Control


On a UserControl holder, 4 buttons are normally used by the ButtonCluster. These are present at
the center of the form. The components can be moved in a demonstrated direction and this is
done by clicking a specific button. The text on these buttons indicates the direction.
The norm is that the product designers must have some information regarding their audience.
Furthermore, if the applications go astray from the Windows look and if it feels excessive, at that
point even the proficient PC clients will not understand what to do. The methodology used
currently requires a custom- made practice for the customers. It will help them in understanding
the new applications.
Four buttons combine to form the UserControl. Buttons need to be kept aligned, and for this,
some points must be kept in mind. Resize events must be responded to when sent to the
UserControl. The button’s text property must be adjusted. The Button Click events must be
surfaced as it permits the customer or user to react to these events.

Making the Graphical Interface of the UserControl


Four buttons of similar size are arranged in the form of a vertical pile. These buttons play a vital
role in the composition of the visual appearance of the main user control. These buttons may be
aligned horizontally to make the user control as common as could reasonably be expected. The
button cluster will be kept basic. The genuine buttons may be delivered utilizing some different
types of buttons.
Now, it is required that we create a new project “Windows Control Library.” This will allow for
the creation of the class “button cluster.” On the UserControl holder make four buttons. By using
the .NET format from Visual Studio, create the buttons which precisely have the same size. Keep
the shape of these buttons generally square. Now to align the buttons vertically at the center use
the Format Align Centers menu. After that, adjust the size of the UserControl. Make it as long as
the height of all the buttons and keep its width equal to a solitary button's width. Try not to stress
over the exact visual estimating because it will be made perfect as we’ll compose the code for it.
The following task performed will be the composition of the code, which will help resize the
button according to containing control size.

Implementing the UserControl Resize Event Handler


At the point when the size of UserControl is adjusted, it is required to make sure that the four
buttons attached must occupy exactly ¼ of the accessible space. Luckily, the design of the
UserControl can be similar to that of a form. In the Properties window, the Event view can be
utilized as well as to help compose the Resize event handler.
private void UserControlButtons_Resize(object sender,
System.EventArgs e)
{
ResizeButtons();
}
The event handler is basically implemented by calling a method that is named accordingly. The
method is named accordingly as it will lessen the requirement of any comment. It also makes it
easy for the user to understand the specific purpose of this code. There is another way to do so by
overriding the method i.e. OnResize method. Keep in mind to call the base class method on the
off chance that it is decided to override the OnResize method. We see that the Resize event has a
method named ‘OnResize’ which invokes the event. This is because the .NET Format utilizes the
prefix ‘On’ for the event methods.
In the case that it is decided that the method OnResize will be overridden, then we can consider
the code shown below for its implementation.
protected override void OnResize(System.EventArgs e)
{
base.OnResize(e);
ResizeButtons();
}
For the implementation of the integrant resize functioning, the OnResize method that is
overridden is considered a good alternative. As mentioned above that both techniques work
perfectly therefore only one either event handler or overridden event handler is required. Mostly
the latter is preferred.
In the event that the user is working on some Format other than .NET, it is essential to
comprehend why overridden methods are preferred over the event handlers. Like in this case the
OnResize method.
Some programming languages use two things i.e. function pointers and procedurals types, which
are both actually almost similar, for their execution. If by any chance a function pointer is
utilized for the execution of the resize functioning and the users then want to execute this event,
then in this case it would not be possible. The reason behind this is that at the same time the
essential function pointer is able to point to just a single function.
Now if we have a look at delegates, they work differently. They keep up an inner list for the
purpose of invocation. These delegates work on the principle of multicasting. Multicasting
permits the delegates i.e. the .NET Format events to point to various event handlers at the same
time. Each time an event is triggered the list informs every one of those handlers. There is no
need to stress over that a programmer will tag along and stamp the functioning of Resize event
handler as the delegates are able to perform multicasting. To expand the functioning of the
UserControls, multicast delegates are preferred as they permit the user to override methods and
utilize the event handlers.

Determining Equal Subdivisions for the Buttons


Whenever the size of UserControl is adjusted, it is informed because now the event handlers are
available to look after this task. This helps in executing a code for the similar resizing of the
buttons.
It is advised that when writing a code, finding out which answer is general enough to be
reasonable in any other situation can be helpful. Expertise says that finding out the decimal part
of a shape say rectangle can be commonly helpful as this function can be used again when
required. It is a smart thought to take another class and execute the functioning in that class at the
point when the code might be commonly helpful. The following code helps to ascertain another
base and top for the shape say rectangle. This rectangle is a fragment of an encircled rectangle.
using System;
using System.Drawing;
namespace UserControlsExamples
{
public class Rectangles
{
private Rectangles(){}
public static Rectangle GetVerticalRectangle(
Rectangle rectangle, int index, int segments )
{
Rectangle r = rectangle;
r.Size = new Size( r.Width,
NewBottom(rectangle, index, segments));
r.Location = new Point(0,
NewTop(rectangle, index, segments));
return r;
}
public static int NewTop( Rectangle rectangle,
int index, int segments )
{
return (int)((float)index / segments *
rectangle.Height);
}
public static int NewBottom( Rectangle rectangle,
int index, int segments)
{
return rectangle.Height / segments;
}
}
}
The above code has a quite simple class. It is easy to find another top dependent on the quantity
of partitions and the real division. Similarly, the base can be computed by making the altitude an
equivalent partition. More significant is how it is decided whenever there is another class. As
mentioned in the previous topics, the most straightforward way is to name the method according
to the function it performs. Here the question arises that in the above class does the method
‘GetVerticalRectangle’ sound according to the function it performs? Is it a decent method for the
button cluster? So the answer to these questions is Yes. Because the thing Rectangle gives a
sensible piece of information concerning the sort of thing this method likely ought to have a
place with. This can be done if you have the required understanding. Otherwise, it is definitely
no ideal science.
With the above code's help, adjusting the size of the cluster buttons can be done without any
problem. The following is the code for resizing the buttons:
private void Initialize()
{
buttons = new Button[]{buttonAllRight, buttonRight,
buttonLeft, buttonAllLeft};
}
private void ResizeButtons()
{
if( buttons == null ) return;
for( int i=0; i < buttons.Length ; i++)
{
buttons[i].Bounds = Rectangles.GetVerticalRectangle(
this.Bounds, i, buttons.Length);
}
}
In the above code, you can see that an array is declared to store every button’s reference. This is
all executed in the ButtonCluster class. Storing the references of the button in an array
encourages repeating above every button. Furthermore, this way the method for rectangles i.e.
Rectangles.GetVertivalRectangle is invoked. The parameter determines the user control’s
rectangle passes above i.e. ‘this.Bound.’ The array’s length demonstrates the quantity of
partitions and the index ‘i’ shows a single partition. In this code, variables are used to decide the
quantity of buttons and the index and it does not depend on the literal values. So this makes the
above code pretty extensible.
A last word on the procedure is altogether. In the case, that a user decides to utilize the Controls
array of UserControl, at that point the user will be more disposed to compose a code that
examines ‘Type” data of every Control. Both the methodologies function admirably. It is not
advised to execute a consistent procedure on the controls of a similar kind because the utilization
of the ‘Controls’ array can lead to a complication on the off chance that the controls of
UserControl are of the same kind.

Surfacing Constituent Events


To complete the task of visual effects of the cluster of buttons the thing that needed to be done is
the adjustment of the Text property. Button.Image can also be utilized for a fine touch by
assigning a realistic arrow.
Technically, the task is not yet completed. The buttons are created so they can send a response to
the Click events. The current event handler will not allow the buyers to use the buttons on the
control to react to the Click events. A solution must be proposed for this marginally tacky issue.
To overcome this problem surfacing constituent controls can be helpful. Although it is not the
best solution. It may seem troublesome to surface the events of the constituent control but it is
not. However, the question arises that what is the need for doing this surfacing?
To foresee what is probably going to come in the extremely not so distant time, the know-how of
the importance of surfacing constituent events and a substitute method will be proved quite
helpful.
Promoting Events in Constituent Controls
Now, at times there is a need to add new controls in the UserControl. These new controls are
added as fields. Two layers of profound UserControl’s controls have their properties enclosed.
Now, make a few assumptions. First of all, assume an instance i.e. userControl1 for UserControl.
Additionally, make an assumption that the instance has a control Button. Now, a code such as
userControl1.Button.Text is required if the user wants to access the button’s Text property. The
property is two layers profound. It is realized by the quantity of the member of operators which
in this case are two. Thus, in the Properties window, the Text property of buttons will not appear.
The user will be able to alter the UserControl’s Button properties technically by supposing that
the Button is declared as public. Next, surfacing the constituent control’s properties and events is
necessary if the user wishes to alter them in the Properties window. Furthermore, surfacing the
events of Button Click is required if the user is to allow composing code that will react to the
clicks of buttons separately.
It is suggested to compose event handlers as they allow the surfacing of the constituent control
events. At the point when the constituent control events are proposed these are then passed to the
events in the new UserControl. So basically there is a need to execute new UserControl events.
The code given below shows how constituent control events are bubbled up to the level of
Interface.
1: private void Initialize()
2: {
3: buttons = new Button[]{buttonAllRight, buttonRight,
4: buttonLeft, buttonAllLeft};
5:
6: buttonAllRight.Click += new EventHandler(OnAllRightClick);
7: buttonRight.Click += new EventHandler(OnRightClick);
8: buttonAllLeft.Click += new EventHandler(OnAllLeftClick);
9: buttonLeft.Click += new EventHandler(OnLeftClick);
10: }
11:
12: private bool IsValidIndex(int index)
13: {
14: return (index >= buttons.GetLowerBound(0) &&
15: index <= buttons.GetUpperBound(0));
16: }
17:
18: public Button this[int index]
19: {
20: get
21: {
22: Debug.Assert(IsValidIndex(index));
23: return buttons[index];
24: }
25: }
26:
27: public event EventHandler AllRightClick;
28: public event EventHandler RightClick;
29: public event EventHandler AllLeftClick;
30: public event EventHandler LeftClick;
31:
32: private void OnAllRightClick(object sender, System.EventArgs e)
33: {
34: if(AllRightClick != null)
35: AllRightClick(sender, e);
36: }
37:
38: private void OnRightClick(object sender, System.EventArgs e)
39: {
40: if(RightClick != null)
41: RightClick(sender, e);
42: }
43:
44: private void OnAllLeftClick(object sender, System.EventArgs e)
45: {
46: if(AllLeftClick != null)
47: AllLeftClick(sender, e);
48: }
49:
50: private void OnLeftClick(object sender, System.EventArgs e)
51: {
52: if(LeftClick != null)
53: LeftClick(sender, e);
54: }
In the above code, see line 6 to line 9. This segment of code adds event handlers that are declared
private. These event handlers are added for the constituent button controls to the Click events. In
the above code, there are 4 events that are declared public i.e. from line 27 to line 30. The names
of these events are LeftClick, RightClick, AllLeftClick and AllRightClick. These events can be
found in the Properties window in the Event view. Event handlers can be added to these public
events by users. There is a time when the events of the Button Click are proposed. If the user has
related the public events and the event handlers, then the inner events verify this situation. If the
case is true, then the events are raised to the UserControl’s surface.
Why surfacing events and constituent control properties is required is the genuine question that
pops up in the mind. Because the event handlers can also be composed using Forms Designer.
Yet the outcome is similar. It does not matter if the event handlers are composed using Forms
Designer or were written.
Other Choice for Member Promotion
The ButtonCluster’s buttons are declared public. It can be supposed that just like these buttons
the declaration of the constituent control is also possible. As a matter of fact, the .NET IDE of
Visual Studio permits the users to do so. When this constituent control is declared public, its
events and properties are straightforwardly accessible to the users.
Some properties have nested reference types. These do not appear in the Properties window and
their property values can be altered, but their events cannot be changed. The altered properties of
these nested reference types have not persevered effectively to the asset document. Basically,
these altered properties are neither kept up during the run and compilation of the program nor
when the IDE is closed. Programmatically, this is considered an error.
In this case, if a person has some knowledge about C #'s historical background, he will be able
to make a few inferences. The foremost is that it can be said that the C# is incompletely the
contrivance of a similar person who assembled Borland’s Delphi. His name was Anders
Hejlsberg. Borland’s Delphi is basically based on the Object Pascal Language. It is its ongoing
forms assists the nested objects. Secondly, the nested properties should have the option to be
altered at design time as in the case that they can be changed programmatically. It is advised to
search for nested objects to perform appropriately in the IDE sooner rather than later. Until
further notice, at the design time, the nested objects don’t persevere the state effectively.
Have a look at the code written below it tells that the user can also attempt the surfacing of
constituent events.
public EventHandler AllRightClick
{
get
{
return buttonAllRight.Click;
}
}
As shown in the above code the event property can be returned in that way if the constituent
event is to be surfaced directly. This way the event property will be permitted to become the
value for an assignment statement. This value will be the right-hand side value. Yet, for the
events, the assignment is not characterized. If the regular tasks are kept in consideration, then the
subtraction and addition assignments are not characterized for them, but they are characterized
by events.
Additionally, it may be attempted to over-burden the assignment operator. It may also be
attempted to make the delegate class a sub-class. Be that as it may, the declaration of classes that
are delegate is done by utilizing a sealed modifier. This implies that it is not possible to make a
delegate class a sub-class.

Creating a PickList Control


The ButtonCluster which is present can be utilized in any application that consists of the
ButtonCluster. This is done by referring to the DLL assembly. Likewise, in any UserControl, this
ButtonCluster can be utilized as a control. Instead of making a solitary, solid control, the
complication is layered and as a result of this, the independent controls are simpler to oversee.
The following control that is constructed is the UserControl. This UserControl has three controls
i.e. a ButtonCluster and two ListBox controls. The person using the ButtonCluster acts as a user
of it and that user only has to concentrate on the new functioning. This is done when the PickList
control is constructed for the ButtonCluster as it is a different UserControl. This is unmistakably
less difficult than constructing a solid control that characterizes the ListBox and ButtonCluster
functioning in a single class.
Now build another UserControl. This is for the execution of the PickList. On the UserControl
color the 2 ListBox. After that, put a panel in the middle. Next, a ButtonCluster is to be placed in
the panel. Now, to keep up the overall arrangements change some settings. Change the Dock
properties of Right ListBox and Left ListBox to right and left, respectively. Change the middle
panel to Fill. At the point when all the adjustments of the UserControl are done, the
ButtonClusters and Listbox keep up their positions in the panel. The code written below helps in
keeping up the arrangement of ButtonCluster:
buttonCluster1.Location = new Point(
panel1.Left + (panel1.Width - buttonCluster1.Width) / 2,
panel1.Top + (panel1.Height - buttonCluster1.Height) / 2);

Adding and Removing Elements


The four types of buttons each have their own functionality and behavior which can further be
implemented in different ways. The “all right” button represented as >> is set to transfer all the
elements contained in the left list to the right list whenever it is pressed. On the other hand, the
“all left” button << does the exact opposite, that is moves the elements from the right to the left
list. If it is required that only the selected elements are to be transferred, then the “right” button >
is used to transfer them from left to the right list while the “left” button < does so from right to
left.
The ListBox is composed of items or elements which are defined as the nested type i.e.,
ObjectCollection. The ListBox controls responsible for moving the elements around are handled
by the method shown below.
1: private void SourceToTarget(ListBox.ObjectCollection source,
2: ListBox.ObjectCollection target)
3: {
4: target.AddRange(source);
5: source.Clear(); 6: }
7:
8: private void MoveAllLeft()
9: {
10: SourceToTarget(listBoxRight.Items, listBoxLeft.Items);
11: }
12:
13: private void MoveAllRight()
14: {
15: SourceToTarget(listBoxLeft.Items, listBoxRight.Items);
16: }
17:
18: private void SourceToTarget(ListBox.SelectedObjectCollection
19: source, ListBox.ObjectCollection target)
20: {
21: IEnumerator e = source.GetEnumerator();
22: while(e.MoveNext())
23: {
24: target.Add(e.Current);
25: }
26: }
27:
28: private void RemoveSelected(ListBox listBox)
29: {
30: for( int i=listBox.Items.Count - 1; i>=0; i--)
31: if(listBox.GetSelected(i))
32: listBox.Items.RemoveAt(i);
33: }
34:
35: private void MoveLeft()
36: {
37: SourceToTarget(listBoxRight.SelectedItems,
38: listBoxLeft.Items);
39: RemoveSelected(listBoxRight);
40: }
41:
42: private void MoveRight()
43: {
44: SourceToTarget(listBoxLeft.SelectedItems,
45: listBoxRight.Items);
46: RemoveSelected(listBoxLeft);
47: }
Source ToTarget method is one which takes the two ListBox.ObjectCollection objects when it is
called by MoveAllRight and MoveAllLeft. In accordance with the direction in which the items
are moved, the lists are relocated as well. All the items present are represented by the
ListBox.ObjectCollection. The object AddRange is set to clear up all the previous elements
shown in the source list. SourceToTarget moves the selected part of the elements and makes use
of two arguments which are:
ListBox.SelectedObjectCollection which is designated as the first argument in this
method.
ListBox.ObjectCollection chosen as the second argument.

The direction of the moving elements is the one that determines the transposition of the
arguments. The enumerator is used to transfer all the selected items from the source to the target
and then RemoveSelected is called upon. An integer is used in lines 31 and 32 where
GetSelected and RemoveAt are defined as such that they only take an integer.
The feature of ListBox includes storage of objects in the list through a special collection thus
adding to the optimization of memory. Even still there is a downside to this, which is observed in
managing the movement of items between lists, more specifically faced when writing general-
purpose utility.

BeginUpdate and EndUpdate


In case of transferring numerous items in a ListBox, it is important not to allow it to update view
every time a new element is added to it or removed from it, doing so slows down the process of
loading.
The process goes such that when items to be loaded are in a large number call
ListBox.BeginUpdate at the start of the update and when the process is complete invoke
ListBox.EndUpdate. Following this process, the list does not show the new items that have been
added to it until the EndUpdate is called, thus preventing longer load time. This can be further
explained by the code given below.
listBox1.BeginUpdate(); // load the list. For example, add the code on lines 21 to 25 of listing
listBox1.EndUpdate();
Most Windows applications have the feature AboutBox, which has its utility due to its one-time
development and multiple times use. Further properties of AboutBox can be accessed by using
the System.Diagnostics.FileVersionInfo class to interpret the assembly metadata.
Surfacing Constituent Properties
Constituent properties are surfaced comparatively in an easier way than the events. When a
control property found in the UserControl is to be surfaced, a public property of the same type is
declared. The constituent control’s property is returned and set in the new control property
contained in the UserControl.
As an example, consider the AboutBoxInfo UserControl is defined and we need to let the users
freely alter the property of PictureBox.Image, the Image property is then surfaced. If the
PictureBox control were set to use a default name, then the new user property statement added to
the user control would surface the constituent image property.
public Image Image
{
get
{ return pictureBox1.Image;
}
set
{ pictureBox1.Image = value;
}
}
Observing it will show that the UserControl now contains the Image Property.
It is not important to use a descriptive name in case of the PictureBox contained within the
UserControl AboutBoxInfo as a private member and there is only one of it. Hence it is quite
okay to use a default name for it because even consumers can’t interact with it and alter it
directly.
A desired feature regarding the constituent controls would be the ability to make them public and
freely manipulate them. Though they can be made public even now, they will not work properly
when viewed in the properties window. The values modified while designing the constituent
controls in the properties window will not be saved when the Visual Studio .NET is closed or
when the application is simply compiled. If such a feature is to be supported, the constituent
properties and events will not need to surfaced.

Implementing the Class ‘ContactInformation’


This section will discuss how we can use the ‘ContactInformation ’ class to store certain
information regarding our UserControl and then, later on, explore this information. Generally,
we can also use this class as a container for a custom class we have created for a project as well.
The following code listing defines two elements of the ‘ContactInformation ’ class, i.e., the
‘contact ’ class and the ‘Contacts ’ object (which will serve as the container).
1: public class Contacts
2: {
3: private ArrayList items;
4:
5: public Contacts()
6: {
7: items = new ArrayList();
8: }
9:
10: public ArrayList Items
11: {
12: get
13: {
14: return items;
15: }
16: }
17: }
18:
19: public class Contact
20: {
21: private string firstName;
22: private string lastName;
23: private string phoneNumber;
24:
25: public Contact( string firstName, string lastName, string phoneNumber)
26: {
27: this.firstName = firstName;
28: this.lastName = lastName;
29: this.phoneNumber = phoneNumber;
30: }
31:
32: public string FirstName
33: {
34: get
35: {
36: return firstName;
37: }
38: set
39: {
40: firstName = value;
41: }
42: }
43:
44: public string LastName
45: {
46: get
47: {
48: return lastName;
49: }
50: set
51: {
52: lastName = value;
53: }
54: }
55:
56: public string PhoneNumber
57: {
58: get
59: {
60: return phoneNumber;
61: }
62: set
63: {
64: phoneNumber = value;
65: }
66: }
67: }
When we go through this entire code listing, we find that the class that has been defined here is
essentially responsible for storing three distinct fields of information (as well as starting these
fields up) - ‘firstName,’ ‘lastName ,’ and ‘phoneNumber .’ The type of information these
fields contain are explained by their namespaces.
Chapter Three
Working with Video Kiosk Using C#

Windows has developed tools in the now not-so-recent past to allow users to use its flexible
graphics programming structures and techniques, which were, frankly, dense and intimidating to
use before then. We shall use the example of a Video Kiosk program to understand how this
toolbox, named “GDI+”, functions, and in doing so learn how to apply these tools in making
unique and creative graphical interfaces of our own, as well as simply using them effectively in
more straightforward projects.
We will cover the following sub-topics:
Introduction to creating Custom Controls.
Making a Control Library.
The ControlPaint class and its implementation in customizing controls.
Virtual Methods.
Overriding Events via Controls.
Exception Handling and caching Exception Flags.
COM Interop and how to use it.
Designing and Implementing Interfaces.
TODO lists.
TimeSpan and MessageBox Classes

An Introduction to GDI+
There has always been an exceptionally robust and capable graphics programming toolkit
available in Windows, referred to as “GDI”, though as we have mentioned it has often been held
back by the technical investment required to learn how to use it effectively. Specifically, GDI
consists of a group of unorganized structures and subroutines and uses API methods that do not
very simply fall in line with each other. In other words, GDI is implemented onto a “canvas”
procedurally.
In contrast, GDI+ is an object-oriented library of graphical tools that encapsulates all of the
above into one structure, i.e. it is an ordered, categorized version of GDI. This lets us peruse one
cleanly divided section of tools at a time, instead of spending half our time diving into a jumble
of structures to find one that we need.
Let’s learn about how GDI has been sorted into GDI+, and the resulting types, classes, and
namespaces that it is made of.
GDI+ Namespaces
The GDI+ Classes are stored in System.Drawing.dll , and are further divided using various
namespaces:
System.Drawing
System.Drawing.Design
System.Drawing.Drawing2D
System.Drawing.Imaging
System.Drawing.Printing
System.Drawing.Text

Combined, these broadly cover the three foci of graphics programming: typography (drawing
text using different glyphs, fonts, sizes, etc.), imaging (non-trivial graphical objects, such as
images, photographs, bitmaps, etc.), and 2D vector graphics (comparatively trivial graphical
objects, such as basic shapes, lines, and curves).

An Introduction to GDI+ Programming


An important concept in the modern era of internet development is statelessness, i.e. code does
not retain information but rather carries flags that are accessed every time it is used. This also
applies to using GDI+: code using these classes require a reminder of their properties and states,
such as font size, shape, position, screen size, etc. In short, almost every piece of information that
relates to the graphics environment has to be explicitly stated every time the code interacts with a
DC, or device context (the “canvas” on which you’re designing a graphic). You cannot cheat by
caching the DC itself, either:

public class CacheGraphics :


System.Windows.Forms.Form
{
Graphics graphics;
public CacheGraphics()
{
graphics = new Graphics();
}
}

This defines a class CacheGraphics that inherits information from Form , and creates a new
Graphics object, storing it in the graphics variable. This does not work because GDI+ is
stateless. Any changes in the DC (which is contained in the Graphics object) will not be
transferred over into the graphics variable as it is only displaying a graphics according to the
information it has been given - it has stored none of said data. Thus, please do not try to create a
Graphics object directly using new, nor store an object of this sort in some field.
Instead, use CreateGraphics to make a new Graphics object to work on every time you need one
(alternatively, get the Graphics object argument from an event handler). Creating a Graphics
object is much more complex that simply calling for a new one, and using this predefined
method ensures that an object is initialized smoothly every time. You will have to provide it all
the state data it needs every time a new graphics operation is called for.
Let’s now look at an example of how to make a graphical interface using GDI+: The
PlayControl:
PlayControl

The PlayControl is a simple example of how to integrate graphics with functionality. A few
things are going on, on the surface level: rounded shapes and buttons, gradients and colors,
images contained in the button spaces, the VideoKiosk trademark logo, the slider on the top of
the interface, etc. As one might expect, the buttons respond to Click events, causing a Click
event handler to be called into function that passes its output to run the requisite code block.
Two things contribute to the reusable design of these graphical controls: one, controls are
implemented separately by the button, and two, the graphical design does not actually do
anything - it only serves to call a function using an IPlayer interface (which will be discussed
later). For example, pressing Play plays something by passing the respective command of the
PlayControl, on the condition that the IPlayer interface is used. Classes allow repeatability of
individual controls and the interface allows us to reuse the entire component. This interface and
its subroutines is described below.

using System;
namespace
VideoKiosk
{
public interface
IPlayer
{
void Close();
void Play();
void Pause();
void Stop();
void FastForward();
void FastReverse();
void VolumeUp();
void VolumeDown();
bool Open();
double Duration();
bool Mute();
void Mute(bool
state);
double Elapsed();
}
}

Owing to this sizeable list of functions, we can conclude that the IPlayer interface can be used to
emulate many modern devices on one computer instead.
Form1.cs , the main form in the VideoKiosk, is used to implement the interface, i.e. all functions
named in the interface are handled by this form. Therefore, we can call Form1 as a player using
PlayControl. To do so, we pass a reference to the PlayControl, contained within its constructor,
to the form as follows:

private PlayControl control = null;


private void Form1_Load(object sender,
System.EventArgs e)
{
control = new PlayControl(this);
control.Show();
}

The PlayControl instances themselves associate and keep track of players. Its constructor is as
follows:

private IPlayer player;


public PlayControl()
{
InitializeComponent();
}
public PlayControl(IPlayer player) :
this()
{
this.player = player;
}

Since PlayControl is dependent on Form1, the PlayControl closes when Form1 does. The above
constructor shows how to call for the default constructor, which is the PlayControl method itself,
and takes no arguments. It must call this constructor since this is the function to initialize the
component. Without doing so, the control objects we wanted to create will not be created, and
the form will not work correctly.
This default constructor is called by this() ,and the subsequent player controls are cached in the
this.player variable field. This has now created a player that we can control using PlayControl.
Let’s look at how, for example, the play functionality is handled when we press the play button.
To begin with, the function player.Play() is called, which runs code in Form1. Form1 contains
the following in our example. This can be different for other sets of interfaces:

void IPlayer.Play()
{
axMediaPlayer1.Play();
}

A more nuanced and practical implementation of a play functionality (as shown in this example
code for VideoKiosk’s play command) would involve things such as event invocation and logic
checks:

private void Play()


{
if(player==null) return;
try
{
player.Play();
PlayerState =
PlayerState.playing;
}
catch
{
PlayError();
PlayerState =
PlayerState.stopped;
}
}
private void playButton1_Click(
object sender, System.EventArgs
e)
{
Play();
}

Generally, it is a good habit not to write code into an event handler itself, instead placing a call to
a method, Play , and using PlayControl’s current context to determine what to do. It uses a
sentinel structure (we may also alternate towards using if-else or other conditional block
statements) to make sure that PlayerState is not null. For exception handling, this method is used
again, ensuring that nothing wrong happens to the player.
If the call (player.Play ) succeeds, PlayerState is updated and the player performs an action.
However, if it does not (for example, in the case of there not being a media file to play) the
Catch block (or else conditional, etc.) is called which runs a PlayError method and stops the
PlayerState. PlayError displays a message box, which you can edit using previously discussed
procedures.

Creating the Graphics for the PlayControl Interface


Creating graphics for a computer program requires one to be proficient at programming and have
a level of artistic capability and thought. Both these qualities are difficult and rare, and good
graphical interfaces are challenging, though interesting, to develop.
We can apply a few different types of graphical inputs, such as vector art, photography,
drawing/sketching, and others. It would be a good idea to leave the art to the artists and
implement their vision into the interface and this means that creating graphics becomes a two-
person job: one artist and one programmer, working in tandem.
Returning to our example, the PlayControl graphics interface consists of a background image
with buttons, sliders, the tracker, and elapsed time (displayed using text) stacked on top.
Background
The background graphic for a Form is assigned using a variable called BackgroundImage . By
default, this is a grey background defined by Windows itself, though you can use any image of
your choosing and assign it to that variable. This also reduces the need for using complex control
to create graphics to use. It is easier to work on a base of a predefined image and edit that instead
of using custom control methods to define something, and speeds up code by not making an
excessive amount of calls and keeping it lean.
Using the remaining Form controls to design regions on top of the background results in straight
lines and boxes, and does not come off as very interesting. We will thus just limit our interaction
to it to adding a background for now.

Buttons and Custom Controls


Let us now look at how we can add buttons to the PlayControl interface, for which we will use
the GDI+ Toolbox. We would prefer to have buttons with rounded edges, and elliptical shapes as
borders, but this is not offered straightforwardly by the toolbox. We’ll have to make some
ourselves. To do so, we will add a custom control to our project that contains all the classes and
methods we might need to implement into the button’s functionality. The following code
describes a basic button made using custom controls, which serves as a basis to all the other
buttons in our interface.

1: public class RoundButton :


2: System.Windows.Forms.Control
3: {
4: private bool hasOutline = false;
5:
6: protected bool down = false;
7:
8: protected virtual Color Getcolor()
9: {
10: Color[] colors = {Color.Silver, Color.Gray};
11: return colors[Convert.ToInt32(down)];
12: }
13:
14: protected virtual Brush GetBrush(bool buttonState)
15: {
16: return new LinearGradientBrush(
17: new Point(2,2), new Point(Width -1 , Height - 1),
18: Color.White, Getcolor());
19: }
20:
21: private int GetPenWidth()
22: {
23: // use button state to adjust pen width
24: return 1 + Convert.ToInt32(down);
25: }
26:
27: private Pen GetPen()
28: {
29: return new Pen(Brushes.Black, GetPenWidth());
30: }
31:
32: public bool HasOutline
33: {
34: get
35: {
36: return hasOutline;
37: }
38: set
39: {
40: hasOutline = value;
41: Invalidate();
42: }
43: }
44:
45: private void DrawButtonOutline(Graphics
graphics)
46: {
47: graphics.DrawEllipse(GetPen(), 1, 1,
48: Bounds.Width - 2, Bounds.Height - 2);
49: }
50:
51: private void DrawButton(Graphics graphics)
52: {
53: graphics.FillEllipse(GetBrush(down), 0, 0,
54: Width, Height);
55: if(hasOutline)DrawButtonOutline(graphics);
56: }
57:
58: protected override void OnPaint(
59: System.Windows.Forms.PaintEventArgs e)
60: {
61: base.OnPaint(e);
62: DrawButton(e.Graphics);
63: DrawGraphic(e.Graphics);
64: }
65:
66: protected override void
OnResize(System.EventArgs e)
67: {
68: GraphicsPath path = new GraphicsPath();
69: path.AddEllipse(0, 0, Bounds.Width,
Bounds.Height
70: Region = new Region(path);
71: Invalidate();
72: base.OnResize(e);
73: }
74:
75: protected override void OnMouseDown(
76: System.Windows.Forms.MouseEventArgs e)
77: {
78: base.OnMouseDown(e);
79: down = true;
80: Invalidate();
81: }
82:
83: protected override void OnMouseUp(
84: System.Windows.Forms.MouseEventArgs e)
85: {
86: base.OnMouseUp(e);
87: down = false;
88: Invalidate();
89: }
90:
91: protected virtual void DrawDownGraphic(
92: Graphics graphics)
93: {
94: Matrix m = new Matrix();
95: m.Scale(1.03F,1.03F);
96: graphics.Transform = m;
97:
98: }
99:
100: protected virtual void DrawGraphic(
101: Graphics graphics)
102: {
103: if(down) DrawDownGraphic(graphics);
104: }
105:
106: protected virtual Brush GraphicBrush()
107: {
108: return Enabled ? Brushes.Black: Brushes.Silver;
109: }
110: }

Let’s break this down:

Constructors, Destructors, and Dispose


Because a control is nothing more than a class, it will have its own constructors, destructors, and
a Dispose method, same as any class. The RoundButton class does not use any of these (aside
from the defaults), but this is a specific case. In other classes in Control.dll (itself a part of
VideoKiosk.dll ) you will notice their presence. Let’s go through what they do:

Control Constructors
A constructor serves to initialize any objects that a class requires. A control constructor serves
the same purpose. Defining a constructor can be ignored in situations where new members do not
require initialization, or no particular method is required to be performed during initialization.
Constructors are usually public, have no return type, and have the same name as their class. For
our RoundButton class we do not need to have a constructor since we do not need any special
form of initialization.
Constructors can be overloaded (i.e. multiples of the same name can be defined and have
different functionalities, inputs, and outputs), and calls to the constructors are resolved
depending on what types of data are given as arguments.
A good idea is to use the constructor to call an initializer method instead of stuffing it full of
code. For example, Form1 uses the InitializeComponent method using its constructor, since it
has multiple controls that need to be initialized.

Control Dispose Methods


C#, being a .NET language, employs non-deterministic destruction, i.e. objects are destroyed by
predefined, and a programmer does not need to define a function to do so. A “garbage collector”
removes cached data, though using this explicitly is tricky, inconvenient, and dangerous, and
thus requires us to write a block of code calling it. Oftentimes we write code that requires
deterministic destruction anyway. This is where we turn towards Dispose methods, as opposed to
destructors. Dispose is a public method that can be easily called, whereas destructors are
unreliable to use in a .NET language.

Destructor
To cover our bases, we’ll describe what a destructor is. It serves to remove and delete cached
data after its use is complete. We won’t often see it as compared to Dispose, but this is what it
looks like:

~RoundButton()
{
}

A few rules about using destructors are:


There can only be one destructor per class.
It cannot take any arguments.
It cannot be overloaded, nor inherited.
It cannot be explicitly called.
The garbage collector uses the destructor, and the user cannot call it.

Conditional Logic and using Arrays


There is a technique where instead of using if-else logic, we can turn to arrays. This makes the
code more streamlined and lean and the IL code for conditional statements is shorter than that for
using arrays. Take the example of the following, which checks a down field and returns a color.
There’s two ways we can do it:

protected virtual Color Getcolor()


{
Color[] colors = {Color.Silver,
Color.Gray};
return colors[Convert.ToInt32(down)];
}

protected virtual Color Getcolor()


{
if( down )
return Color.Gray;
else
return Color.Silver;
}

The former utilizes our method, whereas the latter uses basic statements to achieve the same
purpose and is clearer to understand. The IL code is different between the two because C#
doesn’t allow for typed arrays, and the Boolean must be converted to an integer first before it
will work to index the array.
Also, for very simple conditionals exists the ternary operator ( ? : ). It evaluates a variable as a
Boolean - if true, the first option applies, and if false, the second instead. This produces the least
amount of IL code, but it is difficult to use for multiple, complex conditionals (one might use
case instead).

protected virtual Color Getcolor()


{return down ? Color.Gray :
Color.Silver;
}

You can use any of these methods as you please, and since the method is well-named, you can
code the routine as densely as you like. To summarize, keep the following in mind when
choosing a method:
Array indexing produces concise and specific code.
If-else statements are simple for a few conditions, but can get difficult to decipher
when nesting goes too deep and conditions get too many.
Case statements allow you to order multiple choices.
The ternary operator is a short and sweet method for simple binary choices.

A note about colors: a list of colors with their names is stored in the Color structure, which can
be called using the Getcolor method. We can also specify alpha blend (transparency of the
color), red, blue, and green hues (on a scale of 0 to 255, or base 8) to create a color.
Another note: we have used a Convert class in Getcolor. This class consists of methods to
convert datatypes to a particular type, such as Convert.ToInt32 converting data to a 32-bit
integer. These can accept most datatypes due to them being overloaded, as we have explained
previously. When it isn’t able to, an InvalidCastException is called.
Using Graphics Objects
A Graphics object in GDI+ is like a canvas, and multiple iterations of the object are required to
paint on it. To create a custom drawing, you’ll need to start by creating a Graphics object by
either using a CreateGraphics method from something that has a canvas, such as Windows
Forms, or as a property of the PaintEventArgs argument passed to the Paint event handler, or
other methods. Once you’ve created an instance of the object, you can use the class methods to
create your desired graphic. Take care not to cache this object nor use it in recursive methods
where a previous one is called since these objects are stateless and remember nothing. We’ll
show you how to request a Graphics object from the Paint event handler, and every time a Paint
operation is performed, below.
Paint Event Handler
This handler receives two input arguments:
An object.
A PaintEventArgs instance.

This handler is used most commonly in cases where one wants to create their own drawing. For
now, let us concern ourselves with only two methods, which are directly implemented onto the
PlayControl interface.

private void PlayControl_Paint(


object sender,
System.Windows.Forms.PaintEventArgs e)
{
OutlineControl(e.Graphics);
DrawTrademark(e.Graphics);
}

The Refactored methods in the code above describe their functionality. Then, to create a nice,
rounded shape, we add the first statement to use PlayControl in such a manner (we could not
have created this shape otherwise). Lastly, to add the trademark “VK”, we write the second
statement. The following code elaborates on these functions:

1: private Point[] GetPoints(int shift)


2: {
3: return new Point[]
4: {
5: new Point(3 + shift, 0 + shift),
6: new Point(Bounds.Width - 3 + shift, 0 + shift),
7: new Point(Bounds.Width + shift, 3),
8: new Point(Bounds.Width + shift, Bounds.Height - 3 + shift),
9: new Point(Bounds.Width - 3 + shift, Bounds.Height + shift),
10: new Point(3 + shift, Bounds.Height + shift),
11: new Point(0 + shift, Bounds.Height - 3 + shift),
12: new Point(0 + shift, 3 + shift),
13: new Point(3 + shift, 0 + shift)
14: };
15: }
16:
17: private void OutlineControl(Graphics graphics)
18: {
19: graphics.SmoothingMode = SmoothingMode.AntiAlias;
20: graphics.DrawPolygon(new Pen(Brushes.Black, 2),
21: GetPoints(-1));
22: graphics.DrawPolygon(new Pen(Brushes.White, 2),
23: GetPoints(1));
24: }
25:
26: private void DrawShadowText(Graphics graphics,
27: string s, Font font, Brush foreBrush, Brush backBrush, int x,
int y)
28: {
29: graphics.DrawString(s, font, backBrush, new Point(x, y));
30: graphics.DrawString(s, font, foreBrush, new Point(x-1, y-1));
31: }
32:
33: private void DrawTrademark(Graphics graphics)
34: {
35: Font font = new Font("Haettenschweiler", 24,
36: FontStyle.Bold);
37: DrawShadowText(graphics, "VK", font,
38: Brushes.DarkSlateBlue, Brushes.White, 5, 5);
39: }

OutlineControl modifies the Graphics object to set the SmoothingMode parameter to AntiAlias ,
which blends multiple pixels in a polygon to smoothen it out. The new, smoothened shape is then
returned using GetPoints .
DrawTrademark creates shadows and an inset effect by applying multiple layers of text. These
text layers are created using a method called DrawShadowText that offsets the text to a side or
throughout. The inset effect is created by writing that text offset by -1 and inputting a brighter
color.
Overloading OnPaint
One can either create multiple custom effects on a form every time the graphic is instanced or
create custom controls to handle all of that. To do so, we would need to overload the OnPaint
method. This is the method we use to remake a control (such as our RoundButton) every time it
is painted.
In our PlayControl code listing, we notice that OnPaint is not an event handler, as this method is
a part of the class that is being used to create a custom painting. We do not need to give it an
event flag, but we need to give it a PaintEventArgs object, with the Graphic object we’re using.
If you want a default drawing method followed, you can use an inherited OnPaint method instead
that will also call the event handler. After we’ve made the base drawing, we will insert this code
that makes our custom painting, as we’ve shown in the PlayControl listing by using DrawButton
and DrawGraphic . We’ll go over GDI+ tools to do this soon.
Invalidating a Control
We use the Invalidate method to change a control’s graphics. It calls OnPaint, causing a Paint
event, and forces the control to be repainted. In the PlayControl listing, this is shown on line 72,
in the HasOutline subroutine.

Drawing Shapes and Filling Them


While working with the Graphics class we have many methods to create polygonal and circular
drawings and methods to fill said drawings. For example, for making our buttons we used
DrawEllipse to draw the outline circle of the button (depending on whether HasOutline returns
true) and FillEllipse to color in this region.
These methods work by using a Pen (in the case of Draw methods) or Brush (for Fill methods) to
create their respective graphics. You can use either integer arguments or floating-point inputs to
define the path they need to follow or fill, the difference being that the math in floating-point
inputs is more accurate). How these graphics are created is particularly dependent on what kind
of arguments these methods receive. T there are multiple overloaded functions for each kind of
shape, which are selected and used by the compiler.
For rectangular regions, you can use two points to define its input instead of four, which are
called Rectangle structures and Point structure, respectively (for integer inputs, or RectangleF
and PointF).

Moving Graphics Objects on the Screen using Transforms


GDI+ defines its position using multiple sets of coordinates, such as world coordinates, page
coordinates, and device coordinates. A Graphics method receives a world coordinate when it is
called to function, and these coordinates are translated into page coordinates and then to device
coordinates. All of this happens internally, and allows us as programmers to make changes to
things such as the origin location, pixel size, etc. We use these transforms to provide an illusion
of movement. Specifically, for our example of RoundButton, we use a scaled matrix transform of
the Graphics object’s position and size to do so.

protected virtual void DrawDownGraphic(Graphics graphics)


{
Matrix m = new Matrix();
m.Scale(1.03F,1.03F);
graphics.Transform = m;
}
protected virtual void DrawGraphic(Graphics graphics)
{
if(down) DrawDownGraphic(graphics);
}
protected override void DrawGraphic(Graphics graphics)
{
base.DrawGraphic(graphics);
graphics.FillPolygon(GraphicBrush(), GetPoints());
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
base.OnPaint(e);
DrawButton(e.Graphics);
DrawGraphic(e.Graphics);
}
protected override void
OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
base.OnMouseDown(e);
down = true;
Invalidate();
}

When the button is clicked, the RoundButton control calls the OnMouseDown method (in this
case, we use the base class’ OnMouseDown method, which allows the user to intercept that
event), causing the down field to be set to True to invalidate and update the button. This calls
OnPaint to repaint the control; the base.OnPaint method first, then the custom method. When
down is True (I.e. the button is pushed in), the DrawDownGraphic method creates a matrix
object. This object is scaled and fed to the Graphics object via graphics.Transform to create the
requisite effect. Using transforms is something of an art and you’ll need a good eye, practice, and
retries to get the perfect fit for you.

Creating Shaped Forms, using the GraphicsPath Object


GraphicsPath is a class stored in the System.Drawing. Drawing2D namespace, used to create a
conjoined series of lines and curves. Basically, it is the curve-centric analogue to Windows
Forms.
The objects of this class combine straight lines and not-as-straight curves to create a shaped
form. This combination is sent to the object and is used to define a clipping region for a shape.
For example, the PlayControl’s rounded edges are created like so:

private void ShapeForm()


{
GraphicsPath path = new
GraphicsPath();
path.AddPolygon(GetPoints(0));
Region = new Region(path);
}

This code creates a GraphicsPath object Path . This object receives points using GetPoints, and
is sent into Region to define a region to clip in order to create a form. This is a simple example to
help you understand its basic functionality in the context of our PlayControl, but is fairly lacking
on its own. We will elaborate on this shaped form below.

Defining Clipping Regions


Windows Forms includes a Region property class which represents the control’s clipping region.
These class objects are useful because scaling them is fairly easy owing to them being expressed
in word coordinates. Defining a region yields a form, not just an arbitrary shape.
The following block of code redefines a form’s clipping region and changes it to the one shown
below. It is clipped in such a way that the frame is included as well. The form responds to the
user’s input and moves the clipping region when it is dragged around like it was the original
image.

private void Form1_Load(object sender,


System.EventArgs e)
{
BackColor = Color.Red;
GraphicsPath path = new GraphicsPath();
path.AddString("C#", Font.FontFamily, 1, 75,
new Point(0, 0), new StringFormat());
Region = new Region(path);
}
private void Form1_Click(object sender,
System.EventArgs e)
{
MessageBox.Show("Clicked!");
}

This block of code also changes the background color in the Form Load event. We initialize a
new GraphicsPath object and provide it a string and some information on the font it is to use.
This object is used to create a Region, which is assigned to the form’s Region field.

Linear-scaling Gradient Bushes


As we’ve mentioned previously, we fill and color shapes using Brush objects. There’s a few
kinds of these, such as HatchBrush , LinearGradientBrush , PathGradientBrush , SolidBrush ,
and TextureBrush . All of these produce a different effect when filling a graphic shape. To use a
brush, we either create an instance of a brush type or use the Brushes class explicitly, which
contains methods for these.
To begin with, let’s talk about LinearGradientBrush. This brush type produces a gradient that
transforms from one color to another over a region in a user-defined direction. In the PlayControl
listing, between lines 45 and 50, an example of this in use is shown. The gradient’s start and end
points are provided, and the colors on either end defined.
This Brush can be modified in various ways:
Blend defines how much of either is to exist at any point along the gradient region.
GammaCorrection is a simple yes-or-no Boolean answer to the question of
whether or not gamma correction is applied to the gradient.
InterpolationColors allows a user to create gradients of more colors than just two.
LinearColors is an array of the starting and ending colors of the gradient.
Transform allows us to positionally transform (skew, move, rotate, scale, etc.) a
region.
Rectangle defines a rectangular region and a gradient between the two points used
to define the region.

We have used LinearGradientBrush to paint RountButton and have also added a condition to use
different gradients depending on the state of the down field.
The following listing shows how we can use LinearGradientBrush methods RotateTransform and
SetTriangularShape .

1: using System;
2: using System.Drawing;
3: using System.Drawing.Drawing2D;
4: using System.Collections;
5: using System.ComponentModel;
6: using System.Windows.Forms;
7: using System.Data;
8:
9: namespace GradientBrushDemo
10: {
11: public class Form1 : System.Windows.Forms.Form
12: {
13:
14: [ Chopped out code that was generated by the forms
designer]
15: private System.Windows.Forms.Timer timer1;
16:
17: private float angle = 0;
18:
19: private LinearGradientBrush GetBrush()
20: {
21: return new LinearGradientBrush(
22: new Rectangle( 20, 20, 200, 100),
23: Color.Orange,
24: Color.Yellow,
25: 0.0F,
26: true);
27: }
28:
29: private void Rotate( Graphics graphics,
30: LinearGradientBrush brush )
31: {
32: brush.RotateTransform(angle);
33: brush.SetBlendTriangularShape(.5F);
34: graphics.FillEllipse(brush, brush.Rectangle);
35: }
36:
37: private void Rotate(Graphics graphics)
38: {
39: angle += 5 % 360;
40: Rotate(graphics, GetBrush());
41: }
42:
43: private void timer1_Tick(object sender,
System.EventArgs e)
44: {
45: Rotate(CreateGraphics());
46: }
47:
48: private void Form1_Paint(object sender,
49: System.Windows.Forms.PaintEventArgs e)
50: {
51: Rotate(e.Graphics);
52: }
53: }
54: }

Notice how we’ve used a Timer control to recreate an ellipse at regular intervals. We have used
Yellow and Orange as the two gradient colors. Every time we use the Rotate method, we
increment the floating-point value by five, which is kept in check using a modulo operator.
RotateTransform rotates the brush and SetBlendTriangularShape creates a triangular-shaped
gradient, the three outer points transitioning from one color to the other as it approaches the
center. Finally, we use FillEllipse to fill an ellipse using this brush.
Pens
Pens work similarly to Brushes; you can either create an instance of one to use or call one
explicitly from the Pens class. The code below creates a Pen object, initializing it using a
LinearGradientBrush, and uses it to draw an ellipse.

LinearGradientBrush brush =
new LinearGradientBrush(new Rectangle(0, 0, 2, 2),
Color.White, Color.Green,
LinearGradientMode.ForwardDiagonal);
Pen p = new Pen(brush, 10F);
e.Graphics.DrawEllipse( p, 5, 5, 100, 200);

Tracker Control
We recall that we used the Control class to create our RoundButton class object. We could’ve
improved by using a ButtonBase class, since its functionality and structures are similar and thus
easier to modify. You should always consider what base class to use, so that the modification of
your inherited structure is much easier to achieve. You can also create a Control class from
scratch, which is described later in the book. Sometimes neither of these work and you will need
to create an inherited class with a base that is tiered higher on the control hierarchy, such as
System.Windows.Forms.Control .

Defining Tracker Control


Think of a tracker as a custom-made control. In the PlayControl example, it is the slider at the
top of the interface. It looks and functions similarly to a progress bar to indicate a relative value
between two extremes (i.e. there are three variables, a minimum value, a maximum value, and a
current position). This is an example that will grant you a lot of insight into GDI+ methods and
functionalities.
For our tracker, the minimum defines the left, the maximum defines the right, and the progress
indicator is somewhere in between, which can be determined using a percentage. A complete
score listing for the tracker is included in Tracker.cs, part of Controls.dll package in
VideoKiosk.sln.
Consider the range between your minimum and maximum is 2000. To avoid invalidation and
repaint calls (up to 2000 unique calls), we instead use an arbitrary number of subdivisions and
only repaint the progress indicator when there’s a significant change.
SetStyle
We’ve made a considerable effort to create an appealing combination of foreground control
elements and a background image in creating PlayControl. However, there is no native support
for transparent backgrounds, which forces us into either making the controls look like the
background or just let the background image show. The latter is a less resource-expensive option
and happens to be the cleanest solution. To do this, we’ll need to set up an attribute of the control
called ControlStylesSupport.SupportsBackTransparentColor . Setting this up for the tracker will
allow the background to show through.

public Tracker()
{
this.SetStyle(ControlStyles.SupportsTransparentBackColor,
true);
}

ControlPaint
ControlPaint is a GDI+ class that contains methods to draw 3D shapes such as buttons or sliders.
This class is defined in the Systems.Windows.Forms and consists of methods for designing
buttons, checkboxes, menu glyphs, radio buttons, size grips, etc. We’ll use ControlPaint to make
the visual interface of the Tracker.
Drawing a 3D Border
We want a 3D border for our Tracker. The Tracker class has a DrawBar method that draws a bar
groove for the Progress Indicator to move along. This method takes a Graphics object as an
argument and calls a DrawBorder3D method to operate on it.

protected virtual void DrawBar(Graphics graphics)


{
ControlPaint.DrawBorder3D(graphics, GetX(), GetY(),
GetWidth(), GetHeight(), Border3DStyle.Etched,
Border3DSide.All);
}

This method is static, and thus requires no special ControlPaint object to be created for it.
Boundaries for the region are specified using GetX , GetY , GetWidth , and GetHeight methods
relative to the tracker’s size. The last two arguments are enumerated values, selected from a list
of available members according to our design considerations. This helps create a visual style that
indicates movement along the line, and thus we implement the etcborder-style along all sides of
the border.
Drawing a Button Control
We can go about creating a button for the Tracker in multiple ways. One way involves scaling an
image that is inserted into the control according to the size of the tracker. For instance, let this
image be the shape of a button. To draw this, the control uses Tracker.drawTracker to call
ControlPaint.DrawButton which draws the indicator.

protected virtual void DrawTracker(Graphics


graphics)
{
ControlPaint.DrawButton(graphics,
TrackPosition(), (Height-8)/2, 5, 10,
ButtonState.Normal);
}

The vertical offset is (Height – 8)/2, which puts the button squarely along the line. Tracking the
horizontal position is more complex, and we will use TrackPosition to achieve this.
ButtonState.Normal draws the button in an unpushed state.
Graphics.DrawImage
The buttons included in the PlayControl are of various types, differing most visibly by the image.
Thus, instead of creating unique classes for each button, we can make one class with a subroutine
to change what image it needs to display. The following code describes an ImageButton object,
which is a derivative of RoundButton.

1: public class ImageButton : DarkButton


2: {
3: // TODO: Make sure that the image can be deleted!
4: private Image graphic = null;
5:
6: public ImageButton()
7: {
8:
9: }
10:
11: protected override Color Getcolor()
12: {
13: Color[] colors = {Color.MidnightBlue,
Color.Black};
14: return colors[Convert.ToInt32(down)];
15: }
16:
17: private int GetX()
18: {
19: return (Width - graphic.Size.Width) / 2;
20: }
21:
22: private int GetY()
23: {
24: return (Height - graphic.Size.Height) / 2;
25: }
26:
27: private ImageAttributes GetImageAttribute()
28: {
29: ImageAttributes attribute = new ImageAttributes();
30: attribute.SetcolorKey(Color.White, Color.White,
31: ColorAdjustType.Default);
32: return attribute;
33: }
34:
35: private Rectangle GetRectangle()
36: {
37: return new Rectangle(GetX() + 1, GetY() + 1,
38: graphic.Size.Width, graphic.Size.Height);
39: }
40:
41: protected override void DrawGraphic(Graphics
graphics)
42: {
43: base.DrawGraphic(graphics);
44: if( graphic == null ) return;
45:
46: graphics.DrawImage(graphic,
47: GetRectangle(), 0, 0,
48: graphic.Size.Width, graphic.Size.Height,
49: GraphicsUnit.Pixel,
50: GetImageAttribute());
51: }
52:
53: public Image Graphic
54: {
55: get
56: {
57: return graphic;
58: }
59: set
60: {
61: graphic = value;
62: Invalidate();
63: }
64: }
65: }

Of key importance is how to alter the image so that it fits into the button’s display. For example,
some parts of an image are perhaps unnecessary to display. To remove these parts, you can
screen them out by defining an ImageAttributes object which defines what colors need to be
removed. Also, notice how overloaded DrawImage is so as to account for a variety of input
arguments.
ImageButton, now, uses the ImageAttributes object we created to screen our desired color
(white, in this case) and removes it. If we want only to remove a specific part of the image, make
that part match the same color as given to the ImageAttributes method.

Secondary Topics
We’ve given you a fairly solid overview of how VideoKiosk.sln works but do keep in mind that
the listing for this structure, which includes Control.dll as well, is well over a few hundred lines
of code. These would allow you to simplify your operation of making all of your control buttons
from one base RoundButton object, but we wanted to show you how to use and appreciate GDI+.
However, it does use a few structures from .NET to round out its functionality, which is
tangential to our topic. We’ll discuss them here for your perusal.

The Elapsed Time Clock


VideoKiosk.sln contains an Elapsed Time clock that is updated using a Timer tick. The Timer
control isn’t very resource-intensive, but it does get the job done for one small clock.
It works by raising a flag at time intervals defined in milliseconds. When this interval
(Timer.Interval ) completes, a SetPosition function changes the Tracker object's position using a
value defined by Player.Elapsed that also updates the digital clock that expresses the Tracker’s
time. This works by defining a position in seconds so it can be used for the digital clock and the
extreme values of the Tracker. We create the clock using a method called TimeSpan , which is
initially provided the elapsed time in seconds:
private TimeSpan GetSpan(int position)
{
return new TimeSpan(0,0,0,position, 0);
}
private string GetMask()
{
return "{0}:{1,2:0#}:{2,2:0#}";
}
private string GetFormatted(TimeSpan span)
{
return string.Format(GetMask(), span.Hours,
span.Minutes, span.Seconds);
}
private void ChangePosition()
{
labelElapsed.Text =
GetFormatted(GetSpan(Position));
}

This method also knows how to convert seconds to other larger units of time. Seconds are
converted to minutes and hours automatically. GetMask provides a formatting string to control
the appearance of TimeSpan, which is then used to update the clock. We’ll discuss this
formatting string soon.
Using TimeSpan to Tell Time
TimeSpan can measure time differences to an accuracy of 100 nanoseconds. This is a ”tick” of
the TimeSpan, like the tick of any other clock. TimeSpan can be represented as either a positive
or negative span of time that can measure out to days. The string that TimeSpan stores its time in
is d:hh:mm:ss.ff , where ff refers to fractions of a second. If we needed this string we could use
TimeSpan.ToString() to get time in that format. Performing arithmetic on DateTime values also
yields a string like that.
Formatting Strings
We choose not to use TimeSpan.ToString() and instead do it manually for a more educational
view into the string's inner workings.Format and formatting masks.
GetMask provides you with a formatting mask , which serves to receive data values from the
string. This mask is “{0}:{1,2:0#}: {2,2:0#}”: values in the bracket are format characters that
can be modified, and everything else is literals. The first value represents the zero-based
argument to be changed, and any value after the comma represents the size of the argument. The
third value represents the number and adds a zero to the number if there’s space for it (in the case
of the number being too short). For example, {1,2:0#} represents the first replaceable parameter,
length 2, and currently filled with 0.

Tooltip Control
Windows Forms contains a ToolTip structure. This structure is added to the component tray of a
program, rather than the main form, which causes the Form’s controls to have the ToolTip
property added: this allows you to display a tooltip textbox when the mouse hovers over a
control. They are invisible components and do not show up during runtime automatically. Using
it seems unintuitive at first, and Windows Forms does not seem to support it at a cursory glance,
but it is as simple as adding it to the Component Tray.
Adding Controls to a Toolbox
We create a custom control to add a set of functionalities to a container. Adding a control
automatically adds it to the Windows Forms tab of a toolbox.
Adding controls to a Toolbox requires you to create a Control Class library, into which you will
add the methods you need. You can then access the Customise Toolbox option from the Toolbox
context menu and add this library to the list you want to display in the Toolbox. This will be
expounded upon in later sections of the book.
Catching and Handling Exceptions
We’ve learned how to work with exception flags using the resource protection block and the try-
finally structure. VideoKiosk.sln used the try-catch structure instead. The Try block is the place
where you place your main code to run, and the Catch block is where you add exception-
handling code. If an exception is raised in Try, the Catch block is called. The basic syntax for
this is:

try
{
// code to try
}
catch
{// code to run if an error
occurs
}

You can use multiple Catch blocks for multiple exceptions that each work for a particular class
of exceptions. The following is an example of how to do so - in the method, SetMaximum is a
function to catch an exception called OverflowMaximum the input integer is larger than 32 bits.

private void SetMaximum(double duration)


{
try
{
tracker1.Minimum = 0;
tracker1.Maximum = Convert.ToInt32(duration);
}
catch(OverflowException e)
{
MessageBox.Show(e.Message, "Media Error!",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
As a final note, do not use an exception handling structure if there isn’t an exception to handle.
This serves to clean up code and keep it lean.
Making a TODO List
You can add comments as reminders or headings in Visual Studio .NET using comment tokens,
which are special keywords. These token keywords include TODO and any other

keyword we have defined. To use them, place them immediately after your double forward-slash
comment token ( // ). This places the comments in a task list. We can look through this task list
by going through View > Show Tasks > All, or View > Show Tasks > Comment, in the Visual
Studio environment. To make custom tokens, define them in the Options list or the Environment
> Task List page:
The following code demonstrates an update to the previous code for the ImageButton class,
where we remembered to edit it using a comment. We’ll add the ability to delete the Image
property in the class, which is done by assigning it a DefaultValueAttribute .

1: public class ImageButton : DarkButton


2: {
3: private Image graphic = null;
4:
5: public ImageButton()
6: {
7:
8: }
9:
10: protected override Color Getcolor()
11: {
12: Color[] colors = {Color.MidnightBlue,
Color.Black};
13: return colors[Convert.ToInt32(down)];
14: }
15:
16: private int GetX()
17: {
18: return (Width - graphic.Size.Width) / 2;
19: }
20:
21: private int GetY()
22: {
23: return (Height - graphic.Size.Height) / 2;
24: }
25:
26: private ImageAttributes GetImageAttribute()
27: {
28: ImageAttributes attribute = new ImageAttributes();
29: attribute.SetcolorKey(Color.White, Color.White,
30: ColorAdjustType.Default);
31: return attribute;
32: }
33:
34: private Rectangle GetRectangle()
35: {
36: return new Rectangle(GetX() + 1, GetY() + 1,
37: graphic.Size.Width, graphic.Size.Height);
38: }
39:
40: protected override void DrawGraphic(Graphics
graphics)
41: {
42: base.DrawGraphic(graphics);
43: if( graphic == null ) return;
44:
45: graphics.DrawImage(graphic,
46: GetRectangle(), 0, 0,
47: graphic.Size.Width, graphic.Size.Height,
48: GraphicsUnit.Pixel,
49: GetImageAttribute());
50: }
51:
52: [DefaultValue(null)]
53: public Image Graphic
54: {
55: get
56: {
57: return graphic;
58: }
59: set
60: {
61: graphic = value;
62: Invalidate();
63: }
64: }
65:
66: }

The problem is resolved in line 52 of the above code. After this is done, remember to remove the
TODO token from your code.
A tip for using comments is to add custom tokens to classify what kind of problem something is,
and how it should be handled.
The Process Class
The Process Class, introduced in a previous section of the book, is used to actually receive an
impetus for the rest of the code to run. Process.Start is a static method attached to the Click
event handler for the leftmost ImageButton control on the PlayControl interface.

COM Interop
COM Interop (for interoperability) is a concept in .NET languages that uses COM libraries and
controls in .NET environments since .NET uses Reflection and metadata in its assemblies to
achieve the same goal. These concepts were explained in a previous section as well if you would
like to review them.
Let's take the example of the ActiveX Media Player from VideoKiosk.sln. This is a COM-based
control, and to use it we need to import these controls to our .NET toolbox by selecting
Customize Toolbox from the Toolbox menu. This will import the type library for that COM
control, and allows their usage in a .NET environment. This, of course, comes with the caveat
that you will be using outdated COM structures, and you also will need to create an installer
program to register these commands and methods.
To conclude the discussion we made so far in this chapter, GDI+ is an improvement and a
streamlining of Windows’ powerful GDI toolkit, making it much easier and more lenient to
handle due to the advent of .NET and the addition of new methods and structures. GDI+ is used
for imaging, typography, and vector-based graphics. The structures GDI+ uses are stateless and
require constant streams of their information. Use CreateGraphics to create a Graphics object, or
take the object received by Paint event handlers.
Chapter Four
Personalizing the Visual Studio .NET Framework Environment

There has been considerable investment and research made towards code automation capabilities
for Visual Studio by Microsoft. This serves to provide quality-of-life changes to the way
programmers can code things. We are given the capability to replace tedious and monotonous
processes with automated Wizards, macros, and templates that we can create and use ourselves.
These macros are extremely flexible owing to an extensibility model that lets you customize
every detail of Visual Basic .NET. This chapter will not go over every detail that you can
customize, but rather how to create objects such as Wizards and macros yourself, providing you
with practical information that you can apply and develop yourself.
In this chapter, we will create project templates. Specific topics we will cover are:

Creating Custom Wizards using IDTWizard.


Creating a custom-fit Project Template.
Registering your Wizards and Testing them.
Writing Macros, using Macros IDE

Making a Wizard
A Wizard , colloquially, refers to a series of dialogues that are fed information to create a result.
These structures have become immensely popular thanks to Windows, and the above definition
is a result of that fame. Another more accurate definition is that a Wizard is a series of linear
subprograms, as compared to spatial-based programming that existed at the time. The advantage
that the linear model offers is that it reduces the accessibility of the program at a given step,
which is beneficial in cases such as outcome-based tasks.
An esoteric definition for programmers is that a Wizard is an application or subprogram that
breaks down a task or goal into multiple steps for the user to follow and complete, which is
accomplished using IDTWizard. The user’ interaction with the Wizard is very easy and they only
need to click a Next button to continue most of the time. Developers have a harder time selecting
a Wizard, since all of the back-end needs to be reformulated in order to compress the commands
into one button press. However, it’s actually quite simple to use IDTWizard to create a Wizard,
and the artistic vision of the programmer can be implemented into the console.
The following piece of code is a basic introduction to using IDTWizard to make a Wizard. A
more advanced example is also provided later in this chapter.

using System;
using EnvDTE;
using System.Windows.Forms;
namespace HelloWizard
{
public class HelloWizard : IDTWizard
{
public void Execute(object Application,
int hwndOwner, ref object[] ContextParams,
ref object[] CustomParams, ref WizardResult
retval)
{
MessageBox.Show("Hello Wizard");
retval =
EnvDTE.WizardResult.WizardResultSuccess;
}
}

As you can see, a functional definition of a Wizard is a class that implements the IDTWizard
interface, as defined in EnvDTE. There is only one method defined in IDTWizard: execute.
Putting in the rest is up to the programmer, as is testing if it works.

A Wizard Project
Wizards are basically a collection of classes, so to make one we’ll need to create a class library.
To start making a Class Library Project, go to the New Project dialog, select the Class Library
template, name your project, and press OK. You’re now on your way to making your own
Wizard.
Using IDTWizard
To use IDTWizard to make your Wizard you will need to reference the design-time environment,
i.e. Visual Studio .NET’s extensibility model. To do so, add a reference to the envdte.dll
assembly to the project’s references and refer to the library with the keyword.
There is only one function in IDTWizard, Execute , and it must be provided an array of context,
an array of custom parameters for it to use, an owner handle, and a return value that uses a pass-
by reference modifier.

Pass-By Referencing
We need to create a method that returns a value of a datatype other than void. The parameter that
this method returns can also be given the keyword ref to allow it to return multiple values, by
virtue of them being able to be affected by the caller. Equivalents to ref in other languages
include passing pointers in C++, ByRef in VisualBasic .NET, and var in Delphi. An example
code will describe this method below.
Testing the Wizard
After adding your functionality to the Wizard, you can run it to find out if it works. The
Singleton object DTE contains a method called LaunchWizard , which does exactly that
(specifics are given later in the chapter). The next listing of code is a macro for testing the
HelloWorld Wizard we made earlier, and the one after that is an example of stuff that you can
put in a Wizard.

Imports System
Imports EnvDTE
Imports System.Diagnostics
Public Module Module1
Public Sub Test()
Const Path As String = _
"C:\Temp\HelloWizard.vsz"
Debug.WriteLine("This is running!")
Dim ContextParams(1) As Object
ContextParams(0) = Nothing
DTE.LaunchWizard(Path,
ContextParams)
End Sub
End Module

This macro can be found in Macro IDE: go to Tools > Macros > Macros IDE to open the menu.
Now we need to create a Wizard launch file. This launch file has the extension .vsz and has the
same name as the Wizard’s class library.

VSWIZARD 7.0
Wizard=HelloWizard.HelloWizard
Param=<Nothing>

Place this code in a file named HelloWizard.vsz, and place the file in the same directory as the
HelloWizard.dll. HelloWizard.dll has been registered using regasm.exe, a Visual Studio .NET
utility. The process of registering your Wizards will be explored later in the chapter.

Creating a Project Template for Visual Studio .NET Wizards


Visual Studio .NET contains a lot of methods, tutorials, templates, etc. to help you create all
kinds of projects. It does not, however, have a template for a Wizard. We will show you how to
create a template yourself that you can then access using the New Project dialog.
Visual Studio .NET contains a basic Wizard called VsWizard.dll that you can use to create
project templates. It can be found in “…/Microsoft Visual Studio
.NET/Common7/IDE/VsWizard.dll”. This wizard uses sample files, scripts, and other inputs to
create a project from a predefined template. Thus, we can use it to create a template which saves
us from writing another engine to do so, but we also need to feed it a set of rules, files, and
samples to follow. Our process for creating a project template includes, in no particular order, the
following steps:
Find and use a pre-existing template that is as close to our goal template as
possible. We will use the Class Library template, since a Wizard is already a class
library or DLL.
Modify the pre-existing template by adding new files. For our Wizard we’ll need
to add a .cs file, containing a class that uses IDTWizard. We can use our
HelloWizard code for this.
Update the templates.inf list that contains the files used by our new template.
Rewrite common.js (.js being Jscript .NET), a structure containing generic
methods used by VsWizard.dll. We will need to add code to it, in order to make a
Class Library project that references envdte.dll.
Rewrite default.js to include our template’s generic methods.
Add an icon for our template.
Modify the VsWizard.dll launcher so that it is associated with our template.
Update VSDir to contain our project template, so that it shows in the New Project
Dialog.

This process is, admittedly, quite tedious, but this is a generic and therefore extensible list, which
can be used to create any project template that you would like to. The following sections will
expand upon this checklist, along with how to complete the task that each asks of you, and a
further description of the process. We will also follow the checklist in order.
Creating a New Template from a Pre-Existing Template
Project templates are the methods represented by the icons in the New Project dialog. You can
also create an entire template from scratch as a text file, but this is easier. Take care to consider
what project template you will base yours off as different versions of Visual Studio have
different templates.
To create a template, select one close to yours, which in our case is the Class Library template.
To access this template, go to “…Files\Microsoft Visual Studio .NET\VC#\
VC#Wizards”. Here, the Class Library is represented by CSharpDLLWiz. Follow the below
steps in order to create a new template using this one.
Copy the library folder to the same directory, which will name it “Copy of
CSharpDLLWiz” by default.
Name it whatever you want. We recommend naming this folder
CSharpDLLWizWiz, keeping the convention

These folders have a Scripts and Templates subdirectory that contains a language identifier. For
English users, this identifier is most likely in 1033. The scripts\1033 folder contains the
template’s default.js file, which we will learn to modify later. The templates\1033 folder contains
actual code files that the engine will use to create a template. We will discuss how this works just
after this section. Remember that right now these are still just the same files from the Class
Library template.
Your folder should start to look something like this:

…\Microsoft Visual Studio


.NET\VC#\VC#Wizards
CSharpDLLWizWiz\Scripts\1033
default.js
CSharpDLLWizWiz\Templates\1033
assemblyinfo.cs
file1.cs
Templates.inf

Adding Files to the Wizard Library Template


We can add files that we want for our template to Templates\1033. For now, we don’t need to
add any such file and we can simply use the existing contents. We do, however, need to change
the file1.cs file here so that it contains code for a Wizard template. It would look something like
this:

using System;
using EnvDTE;
namespace [!output SAFE_NAMESPACE_NAME]
{
/// <summary>
/// Summary description for [!output
SAFE_CLASS_NAME].
/// </summary>
public class [!output SAFE_CLASS_NAME] :
IDTWizard
{
public [!output SAFE_CLASS_NAME]()
{
//
// TODO: Add constructor logic here
//
}
public void Execute(object Application, int hwndOwner,
ref object[] ContextParams,
ref object[] CustomParams, ref wizardResult retval)
{
//
// TODO: Add your custom code here
//
retval = EnvDTE.wizardResult.wizardResultSuccess;
}
}
}

Notice how this is very similar to our original HelloWizard code, with the addition of
SAFE_CLASS_NAME replaceable tokens. Again, you don’t need to change any files in this
folder, but you can inspect them to see what they do and modify them if you want to.
Modifying default.js
default.js is stored in Scripts\1033. To modify it for our template, we need to make one small but
important modification to it that allows our Wizard projects to reference envdte.dll. We need to
coordinate this with common.js as well, which is described in the next section. For now, let’s see
how we will modify default.js:

1: // (c) 2001 Microsoft Corporation


2:
3: function OnFinish(selProj, selObj)
4: {
5: var oldSuppressUIValue = true;
6: try
7: {
8: oldSuppressUIValue = dte.SuppressUI;
9: var strProjectPath = wizard.FindSymbol("PROJECT_PATH");
10: var strProjectName = wizard.FindSymbol("PROJECT_NAME");
11: var strSafeProjectName = CreateSafeName(strProjectName);
12: wizard.AddSymbol("SAFE_PROJECT_NAME",
strSafeProjectName);
13:
14: var bEmptyProject = 0;
//wizard.FindSymbol("EMPTY_PROJECT");
15:
16: var proj = CreateCSharpProject(strProjectName,
17: strProjectPath, "defaultDll.csproj");
18:
19: var InfFile = CreateInfFile();
20: if (!bEmptyProject)
21: {
22: AddReferencesForWizard(proj);
23: AddFilesToCSharpProject(proj,
24: strProjectName, strProjectPath, InfFile, false);
25: }
26: proj.Save();
28: }
29: catch(e)
30: {
31: if( e.description.length > 0 )
32: SetErrorInfo(e);
33: return e.number;
34: }
35: finally
36: {
37: dte.SuppressUI = oldSuppressUIValue;
38: if( InfFile )
39: InfFile.Delete();
40: }
41: }
42:
43: function GetcSharpTargetName(strName, strProjectName)
44: {
45: var strTarget = strName;
46:
47: switch (strName)
48: {
49: case "readme.txt":
50: strTarget = "ReadMe.txt";
51: break;
52: case "File1.cs":
53: strTarget = "Class1.cs";
54: break;
55: case "assemblyinfo.cs":
56: strTarget = "AssemblyInfo.cs";
57: break;
58: }
59: return strTarget;
60: }
61:
62: function DoOpenFile(strName)
63: {
64: var bOpen = false;
65:
66: switch (strName)
67: {
68: case "Class1.cs":
69: bOpen = true;
70: break;
71: }
72: return bOpen;
73: }
74:
75: function SetFileProperties(oFileItem, strFileName)
76: {
77: if(strFileName == "File1.cs" || strFileName == "assemblyinfo.cs")
78: {
79: oFileItem.Properties("SubType").Value = "Code";
80: }
81: }

The template wizard is designed to use external JScript functions. There are four of them
mentioned here: OnFinish , GetcSharpTargetName , DoOpenFile , and SetFileProperties . These
are used exclusively by the template wizard to call for the Wizard Library.
SetFileProperties sets up a flag to mention that the .cs files contain code.
DoOpenFile opens the class module file in Visual Studio .NET.
GetcSharpTargetName changes the name of the file. We use it to change file1.cs’
name to class1.cs instead.
OnFinish completes the substitutions for the methods and parameters in the file,
and ties up the package.

The small change that we needed to make to file1.cs is replace AddReferenceForClass(proj) to


AddReferenceForWizard on line 22. This method isn’t defined anywhere yet and the next section
modifies common.js to define and include this method.
Modifying common.js
The structure of the Project Template is based on the shared wizard engine, the folder structure,
the template files, and two JScript files that combine to create a project template. This is dense,
unwieldy system, but it is what we have.
common.js is a script common to all templates, stored in ..\Microsoft Visual Studio
.NET\VC#\VC#Wizards\1033. We have to modify this file to include references to our new
template and subsequent projects. Add the following code to common.js to include the
AddReferenceForWizard method.

Description:
oProj: Project object
********************************************************/
function AddReferencesForWizard(oProj)
{
var refmanager = GetcSharpReferenceManager(oProj);
var bExpanded = IsReferencesNodeExpanded(oProj)
refmanager.Add("System");
refmanager.Add("System.Data");
refmanager.Add("System.XML");
refmanager.Add("envdte");
if(!bExpanded)
CollapseReferencesNode(oProj);
}

We made this using the AddReferenceForClass method, adding a call to the refmanager to refer
to envdte.dll. We can do this because the Class Library structure is already very similar to ours.
If we’re making a template from scratch, we would need to create other methods and classes.
Now all that’s left is to create a VSDir file and the Wizard Launcher file.
The Wizard Launch File
We’ve already discussed how to create a Wizard using IDTWizard in a previous section titled
“Creating a Custom Wizard”. However, we do not need to create a Wizard from scratch. We’ll
modify the Class Library template’s Wizard and use that. We will only be telling the New
Project dialog the Wizard it needs to select. The Wizard Launch files for all Project Templates
are stored at the directory “…\Microsoft Visual Studio .NET\VC#\CSharpProjects”. The Wizard
Launch file for the Class Library is stored in CSharpDLL.vsz . Copy this file, rename it to
something like CSharpDLLWiz.vsz , and modify the code within to refer to our template, as
follows:

VSWIZARD 7.0
Wizard=VsWizard.VsWizardEngine
Param="WIZARD_NAME =
CSharpDLLWizWiz"
Param="WIZARD_UI = FALSE"
Param="PROJECT_TYPE = CSPROJ"

The only change we made to the original file is to change the Wizard to refer to our template’s
wizard. The other parameters are just conditional values. Now all that’s left is to create VSDir
and test our template.
Creating a VSDir File
These files define what information is received by the New Project and Add Item dialogs and
how items in those lists are displayed. They require two things - an icon and a name. Specify the
connection between these two things and the template you want them to refer to. The listing for
VSDir is as below, written in a single line - we will explain how this works after:

CSharpDLLWiz.vsz|{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}|Wizard
Library|
20|#2323|{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}|4547|
|WizardLibrary

This one line contains the existing project template’s items. VSDir files are stored in “…
\Microsoft Visual Studio .NET\VC#\CShaprProjects\CSharpEx.vsdir” and this folder will also
contain your Wizard Launch file.
This one line is divided into fields by “pipes” (the “ | ” symbol). The following table breaks these
fields down in order of appearance, and describes what they do.
Relative Path Name CSharpDLLWiz.vsz Specifies the wizard launch file using a
relative path. Store the .vsz file in the same
directory as the .vsdir file.
{FAE04EC1-301F-11d3- CLSID package A GUID representing a resource DLL. This
BF4B-00C04F79EFBC} particular GUID refers to something named
the C Sharp Editor Factory.
Wizard Library Localized name This is the template's localized name and the
name that will appear in the New Project
dialog.
20 Sort priority Determines the order in which elements are
listed. A sort priority of 1 is the highest.
#2323 Description A string or resource identifier containing a
localized text description of the template.
{FAE04EC1-301F-11d3- DLLPath or CLSID package Contains a GUID reference to an EXE or
BF4B-00C04F79EFBC} DLL resource that contains icons for the
template.
4547 Icon resource ID Indicates which icon to use from the resource
file referred to from the previous entry.
<blank> Flags Bitwise flags, not used by our template. You
can refer to the Visual Studio .NET help for
VSDir files for individual flag values.
WizardLibrary Suggested base name Specifies the default name for the template.
Our entry represents a project, therefore, the
root name for Wizard Library projects will be
WizardLibrary. The first new project will be
WizardLibrary1, and so on.

This template is used to create the following entry in the New Project dialog box:

Now that everything is done, lets test our template by creating a new project. Go to File > New >
Project, click on the Wizard Library icon, and press OK. You should now have a new Class
Library project with an assemblyinfo.cs file and a file named WizardLibrary1.cs, which should
contain a basic execution of IDTWizard. Do double check that a reference to envdte.dll exists.
A final note for this section regarding the project’s template is that it’s a combination of shared
files from across the base class and the environment. An important one of these is
DefaultDLL.csproj file, which is located in “…\Microsoft Visual Studio .NET\VC#\VC#Wizards
folder. All DLL-based projects refer to this template. Also, most of the process of creating a
template is copy and pasting things, rather than creating things from scratch. Make a template if
you are going to use a custom project structure often to simplify tedious tasks and streamline
your process.
Now that all of this works, let’s use these to make something that automates tasks for you.

Extending Visual Studio .NET with Wizards


A wizard is a simple way to create a task automation that benefits newer programmers. Creating
a wizard allows your team to use the more unique aspects of .NET programming more easily.
Let’s make a wizard that creates a strongly-typed collection , a collection that inherits from
ReadOnlyCollectionBase or CollectionBase . Methods in these classes include IList , IListSource
, IEnumberable , which results in you creating a collection structure that behaves like an array
and can be sorted and used by a DataGrid control and can be compiled into an ADO.NET
dataset. This wizard already exists and it is named TypedCollectionWizard and it implements
methods from System.Collections.CollectionBase. It works by creating a new class that inherits
from the previous one, adding an indexer and an Add method. We will use this example to
understand how to make macros and program against the Common Environment Object model.

Writing a Macro
We now already have a basic understanding of how to create, write, and test wizards, which will
serve us well in writing macros as well, alongside things such as C# programming and Windows
Forms interfacing. Let’s continue with how to write a macro.
Macro support is a part of Visual Studio .NET’s extensibility model, alongside but separate from
Macros IDE. Macros are written using Visual Basic .NET. Macros IDE is a project-centric
environment, and the macro files created are stored with .vsmacro extensions, though Visual
Basic code can also be communicated to it.
To start, open Macros IDE from Tools > Macros > Macros IDE. Using this is similar to Visual
Studio .NET. In this new environment, select the Project Manager from the View menu. To
create a new macro, select an existing module or create a new one (a module is a sourcecode
file). Add a simple subroutine (read: method) to it and see if it works by starting a debug process
from Debug > Start. Here’s an example of a macro which simply produces a message box that
says “Hello World!”:

Sub HelloWorld()
MsgBox("Hello
World!")
End Sub

Let’s move on to a more practical example of a macro that adds a new class to an existing
project, similar to how we will reconstruct TypedCollectionWizard later. The following macro
does exactly that: it adds a new class file to an active project’s directory, and the second (empty)
entry is where the name of the new class would go. By default, an appropriate name is produced
by the method itself:

Sub TestNewFile()
DTE.ItemOperations.AddNewItem(
_
"Local Project Items\Class", "")
End Sub

Notice the DTE namespace keyword. The following section is devoted to giving a brief overview
of this keyword, referring to the design-time environment.
The Common Environment Model
A DTE is a design-time environment object, referred to by internal documentation as a Common
Environment Model, or the automation model, or the extensibility model. We will continue to
refer to it as a DTE. It is the root of a project, representing an object model allowing access to the
capabilities of Visual Studio .NET. DTE uses interfaces to create an object-oriented accessibility
within the Visual Studio .NET environment, which is, in effect, a method for automation. The
documentation for this model is very large, and perusal is at one’s own risk.
For our current concern, we’ll only use a small section of that manual to apply DTE for macros
and C# code, which should serve to introduce you to the core concepts of using it. A good way to
think about DTE is as a mask that interacts with Visual Studio .NET, including menus,
documents, macros, etc.

Writing Code, using Macros


We’ve learned how to reuse Project templates to generate new code, but we can also change code
on the fly during runtime using DTE. This would look something like as follows:

1: Public Sub TestWriteCode()


2: Try
3: Dim item As ProjectItem = _
4: DTE.ItemOperations.AddNewItem( _
5: "Local Project Items\Code File")
6:
7: Dim defaultNamespace = _
8: item.ContainingProject.Properties. _
9: Item("DefaultNamespace").Value
10:
11: Dim code As CodeNamespace = _
12:
item.FileCodeModel.AddNamespace(defaultNamespace)
13:
14: Dim editPoint As EditPoint = _
15: code.StartPoint.CreateEditPoint
16:
17: editPoint.LineDown(2)
18:
19: editPoint.Insert(DateTime.Now.ToString() +
vbCrLf)
20:
21: Catch e As Exception
22: MsgBox(e.Message, MsgBoxStyle.OKOnly,
"Error")
23: End Try
24: End Sub

What this code does is that it:

creates a C# file, by calling for a new one and obtaining a reference to the
ProjectItem for it.
adds a default namespace, and formats a namespace element.
inserts text into that file, by assigning edit points. Text can be added here either
manually or using Add methods.

This file is added to the current project, but it cannot create a project on its own. Running this
code results in the following:

namespace
TestWizardOuput
{
5/9/2002 5:12:23 PM
}

The TypedCollectionWizard uses an incomplete template of code alongside a DTE to generate


its strongly-typed collection. Let’s move on to how we can generate functional code
automatically.

Code Generator
You can create a code generator by centering it around structures that exist in all instances of
your code. Add string-based inputs to work with these structures and add dynamic functionality
to it. For example, the templates’ code generator Wizard is written as follows:

1: using System;
2:
3: namespace TypedCollectionWizard
4: {
5: /// <summary>
6: /// Summary description for Wizard.
7: /// </summary>
8: public class Wizard
9: {
10: /// <summary>
11: /// Parameter 0 is the class name; parameter 1 is the type
name;
12: /// parameter 2 is the optional setter; parameter 3 is the
comment.
13: /// </summary>
14: private const string template =
15: " // Code generator by [email protected]\r\n" +
16: " {3}\r\n" +
17: " public class {0} : System.Collections.CollectionBase\r\n"
+
18: " {{\r\n" +
19: " public {1} this[int index]\r\n" +
20: " {{\r\n" +
21: " get{{ return ({1})InnerList[index]; }}\r\n" +
22: " {2}" +
23: " }}\r\n\r\n" +
24: " public int Add({1} value)\r\n" +
25: " {{\r\n" +
26: " return InnerList.Add(value);\r\n" +
27: " }}\r\n" +
28: " }}\r\n";
29:
30: private const string setter =
31: "set{ InnerList[index] = value; }\r\n";
32:
33: private string name;
34: private string typeName;
35: private bool hasGetter = true;
36: private bool hasSetter = true;
37: private string comment;
38:
39: public Wizard(string name, string typeName, bool
hasGetter,
40: bool hasSetter, string comment)
41: {
42: this.name = name;
43: this.typeName = typeName;
44: this.hasGetter = hasGetter;
45: this.hasSetter = hasSetter;
46: this.comment = comment;
47: }
48:
49: private string GetSetter()
50: {
51: return hasSetter ? setter : "\r\n";
52: }
53:
54: private string Getcode()
55: {
56: return
57: string.Format(template, name, typeName,
58: GetSetter(), comment );
59: }
60:
61: public string GetTemplate
62: { get{ return template; } }
63:
64: public string Code
65: { get{ return Getcode(); }}
66:
67: }
68: }

This code is fairly straightforward, making a template that uses parameters that vary from class
to class, and using them when needed upon calling Getcode. More importantly, we can use this
standalone to test whether it works for the Wizard. This results in the following code, which is
syntactically correct and works as intended for the Wizard.

public class Customers :


System.Collections.CollectionBase
{
public Customer this[int index]
{
get{ return (Customer)InnerList[index]; }
set{ InnerList[index] = value; }
}
public int Add(Customer value)
{
return InnerList.Add(value);
}
}

Let’s now make an interface to interact with this code:

Implementing the Wizard UI


We’ve used the Add Indexer Wizard’s User Interface in our example. To implement it, we’ve
used a few tricks here and there. The following section discusses them:
User Interface Strategies:
We use property methods to interact with controls and any change in the control only requires a
singular change in its reference. The following is the code for the name of the collection typed
into the Textbox UI.
private string ClassName
{ get{ return textBoxClassName.Text;
}}

Any changes to the control of the Textbox only need to be referred in one place in the GUI code.

Another thing you can do is to validate field input in the UI as well as the class, using regular
alphanumeric expressions. The following code confirms this.

private void DoValidateField(Control control, string


value,
string expression, string errorText)
{
if( !Regex.IsMatch(value, expression))
{
control.Focus();
throw new Exception(errorText);
}
}
private void ValidateClassName()
{
DoValidateField(textBoxClassName,
ClassName, @"^\w$|^\w[A-Za-z0-9]+$",
"Valid class name is required");
}
Dialog Form Strategies
We use FormWizard to create a dialog form. A tip for dialog forms is to make a static method,
called Execute , which accepts inputs and returns outputs for the form. The user only needs to
worry about the inputs and outputs, not the form as Execute handles them. The following
demonstrates:

public static bool Execute(ref string


generatedCode)
{
using(Form1 form = new Form1())
{
if( form.ShowDialog() == DialogResult.OK)
{
generatedCode = form.Code;
return true;
}
else
return false;
}
}

Ultimately, the user will be the TypedCollectionWizard. When IDTWizard is implemented it


only needs to use this static method, feed it an input, and it will return an output, which it can
then use. This can also be applied to Windows Forms applications. The alternative involves
rewriting and re-evaluating the code, in effect writing the code twice.
The form is displayed using the following piece of code.

string generatedCode = string.Empty;


If(FormWizard.Execute(generatedCode))
// do something

Implementing the Wizard


We’ve set up the code generator using a static method that requires nothing more than an input to
function. Everything is handled internally. With this completed, the rest of the Wizard is fairly
easy to implement. Adding functionality to a Wizard occurs by using the IDTWizard.Execute
method to implement our code, such as follows:

1: using System;
2: using System.IO;
3: using EnvDTE;
4: using System.Windows.Forms;
5:
6: namespace TypedCollectionWizard
7: {
8: /// <summary>
9: /// Summary description for Class1.
10: /// </summary>
11: public class CollectionWizard : IDTWizard
12: {
13: // Implements IDTWizard.Execute
14: public void Execute(object Application,
15: int hwndOwner, ref object[] ContextParams,
16: ref object[] CustomParams, ref wizardResult retval)
17: {
18:
19: string generatedCode = string.Empty;
20: if( FormWizard.Execute(ref generatedCode))
21: {
22: WriteCode((DTE)Application, generatedCode);
23: retval = EnvDTE.wizardResult.wizardResultSuccess;
24: }
25: else
26: {
27: retval = EnvDTE.wizardResult.wizardResultCancel;
28: }
29: }
30:
31: private void WriteCode(DTE dte, string
generatedCode)
32: {
33: try
34: {
35: DoWriteCode(dte, generatedCode);
36: }
37: catch(Exception e)
38: {
39: MessageBox.Show(e.Message, "Error Writing Code",
40: MessageBoxButtons.OK, MessageBoxIcon.Error);
41: }
42: }
43:
44:
45: private void DoWriteCode(DTE dte, string
generatedCode)
46: {
47: ProjectItem item = dte.ItemOperations.AddNewItem(
48: @"Local Project Items\Code File", "" );
49:
50: string defaultNamespace =
51: (string)item.ContainingProject.Properties.Item(
52: "DefaultNamespace").Value;
53:
54: CodeNamespace code =
55:
item.FileCodeModel.AddNamespace(defaultNamespace,
0);
56:
57: EditPoint editPoint = code.StartPoint.CreateEditPoint();
58: editPoint.LineDown(2);
59: editPoint.Insert(generatedCode);
60: }
61: }
62: }

This code completes using IDTWizard, displays the form, writes code using the code generator if
Execute is true using WriteCode, which manages error handling using a try-catch structure, and
generates a code file using DoWriteCode.
We’ve used DTE in this code by casting an Application parameter onto a DTE object, and using
that to generate source code.
This demonstrates the automation capabilities of Visual Studio .NET, and it is one of the reasons
it is so beloved by software programmers. Now to test the Wizard!

Completing the Sample Wizard Launch File


Creating a Wizard Launch file is simple and we only need to provide the wizard's name and
mention that it doesn’t need to be passed arguments. This file has the extension .vsz, and it is
read every time the Wizard is loaded. The following describes the Wizard Launch file for
TypedCollectionWizard, which is saved in the same directory as its library file. This isn’t
necessary, but it’s an easy shortcut.

VSWIZARD 7.0
Wizard=TypedCollectionWizard.CollectionWizard
Param=<Nothing>

1. The first line must be added as is.


2. The second line defines the assembly name, and the class name that contains the
IDWizard implementation.
3. The other parameters define what kind of parameters are to be sent to the Wizard,
if any.

Let’s move on to a more complicated example. The following is the Wizard Launcher file for the
C# Indexer Wizard that works alongside the Wizard Engine. You can pass any kind of
parameters into the Wizard using this, such as the Wizard’s name and the Project type.
VSWIZARD 7.0
Wizard=VsWizard.VsWizardEngine
Param="WIZARD_NAME =
CSharpIndexerWiz"
Param="PROJECT_TYPE = CSPROJ"

Registering Wizards
The Wizard requires access to the Registry, but does not need to be a member of the Global
Assembly Cache (or GAC). To this end, we can register it using regasm as follows:

c:\winnt\Microsoft.NET\v1.0.3705\regasm
c:\temp\TypedCollectionWizard.dll
/codebase

This is the default path for the .NET framework. If there’s a different directory in place of
c:\temp , use that. /codebase stores these path in the registry using file:// . Again, the Wizard is
still a .NET structure, only accessing the registry. It is not a COM component. There will be an
explanation at the end of the chapter.
A quick note, the GAC is a cache for all the assemblies being used by the machine. A Wizard is
not a permanent part of that list, and thus it doesn’t need to be registered. The GAC is, in effect,
a giant folder that contains and catalogues assemblies for easy use. We recommend looking into
a .NET utility called GACutil.exe.
Testing the Wizard using a Macro
Let’s use our macro that we made at the beginning of the chapter to test our Wizard. Replace the
macro’s constPath variable with the address to the TypedCollectionWizard, and run it.
Running the Wizard from the Command Window
We can use our macro from the previous section to run our Wizard from the Command Window.
Select View > Other Windows > Command Window. We’ve created a test macro called
MyMacro, stored it in a module named Module1, and named the method inside
TestCollectionWizard. All of this combined, we call our Wizard with this line of code:

Macros.MyMacros.Module1.TestCollectionWizard

A list of commands will pop up when you type the word Macros, via Intellisense.

Secondary Topics
The chapter introduced into a wide variety of tools and concepts such as JScript, gacutil.exe,
regasm.exe, etc. These are structures with extensive documentation, and a more thorough
introduction to these concepts is in order:

Returning to JScript
We used a bit of JScript to implement our templates, which is done by calling an external
compiler. However, JScript is a completely different and just-as-fleshed-out language as
compared to Visual Basic .NET and C#. You’re likely to find code written in this language in
things such as clientside code for webpages and ACT (a testing automation application
developed by Microsoft). The following checklist describes how you may go about writing some
JScript .NET code.
Open NotePad.
Write print.(“Hello World!”) .
Save this file as HelloWorld.js, and remember its directory. Close the file.
Open the command prompt, and run the file by calling the compiler as follows:

c:\winnt\Microsoft.NET\Framework\V1.0.3705\jsc
Hello.js

Using the regasm Utility


Wizards are an important part of Visual Studio .NET that are attached to it using COM. To do
so, we use the regasm utility. Two forms that works best for this are:

regasm assemblyname
/codebase

regasm assemblyname
/unregister

1) regasm simply refers to the utility. assemblyname is the name of the assembly
containing the Wizard DLL. /codebase adds the code to the registry. It is technically
all that is required to make a complete call, though it does provide a warning to use a
strongly-worded name (by using sn.exe, for example) to avoid version problems.
2) Similar to the above, except it uses /unregister to unregister the Wizard from the
registry.
The wizard does not use COM. It is required to register the DLL into the registry to load it into
the Visual Studio .NET environment.
To read the registry assembly, do:

regasm assemblyname
/regfile:regfile

where assemblyname would refer instead to your assembly and the second regfile refers to a .reg
extension file.
Programming has come a long, long way from what it was ten years ago, and it continues to
grow and develop at an exponential pace. We’ve developed things such as exception handlers,
that have a contingency plan for pretty much every situation that we can imagine.
As we’ve mentioned, the field of programming is ballooning at an extremely rapid pace, and it’s
quickly becoming less and less probable that one person can know everything about
programming. Specialization is the norm now as it is simply impossible for someone to know
everything about everything. Just in this one chapter, we’ve touched on three massive languages
- Visual Basic .NET, JScript (or JavaScript), C# - and utility programs GACutil.exe and
regasm.exe. A programmer now only has a basic understanding of the underlying concepts but
needs to opt in to one of these fields. They can focus on game development, or web design, or
even more utilitarian application/software programming. Anything you can imagine.
Automation also is beginning to form a real concern to programmers (and humans as a whole),
based on the strength of modern computers and the speed at which they can grasp concepts given
a ruleset. In games requiring intellect and complex decision-making, such as chess, the Chinese
game Go, and DotA 2, programs that have used advanced automation to repeat processes and
develop optimal strategy have far overtaken the capability of humans. Programming can be left
to programs themselves, now.
Conclusion

We have now come to the end of our journey. Even though you might have felt C# to be a bit
difficult and at times, frustrating to understand, regardless you have increased your programming
knowledge. In the world of programming, experience is the best teacher you can ever find. While
we have tried our best to provide you with adequate explanations of concepts and advanced
topics, you might still feel that something was missing. If that’s the case, then you are on the
right track of learning. Anything that you feel is ambiguous, will serve as an impetus to a
specific topic for research which will expose you to even more things, causing a domino effect.
Every chapter in this book has tried to cover all of the aspects of C# programming to a certain
extent, however, it is out of the scope of this book to completely dominate every advanced
programming element of C#. Thus, it is important to provide the readers with the C#
programming’s most important central information, if not the complete package. It is highly
recommended that you research the aspects which confuse you, this will help clarify your
concepts at a level which would otherwise have not been possible.
In short, we have explored the fundamental principles of object-oriented programming in the first
chapter and learned how C# implements these principles through various functions. In the next
chapters, we discovered the extended functionalities in C# programming such as using the
‘Reflection’ function in the .NET framework to extract information from assemblies and use
them. Finally, we move on to truly advanced C# programming topics such as using ‘GDI+ ,’
working with Visual Studio .NET and the Event logger, and last but not least, understanding how
to effectively use ‘UserControls ’ to create the interface of an application. All of these topics
collectively define the C# programming paradigm and we hope that the reader learns and
understands the core concept of every topic and discussion in these chapters. Exposure to a
programming language can go a long way in a person’s programming career as someone might
have to reverse engineer a mechanism built using programming languages like C#, C++, etc. So
it’s recommended always to have the eagerness to learn a programming language no matter how
intriguing it may seem.
References

Advanced C# Programming by Author: Paul Kimmel

You might also like