Computer Program
A sequence of data instructions created by a programmer
Instructions that tell the computer what operations it should execute
Instructions that tell the computer how it should execute an operation
Instructions written in a special programming language, for example, C#, Java, C++, or COBOL
More powerful than others, for example, C#
Better for developing applications requiring fast processing, for example, C
Better for developing web-based software applications, for example, JavaScript
Better for developing computer games, for example, C++
Better for data analytics, for example, Python
Better for scripting, for example, Perl
The preceding points should help us understand that there are many programming languages available for software developers, but they all have concepts that can be applied across many of the languages. So, by the time we finish reading this book, entering and running all the example code, and doing all the exercises, we will be in a strong position to recognize and apply constructs in the Java programming language or the C++ language and indeed other programming languages, as well as our main focus, the C# language.
Programming Languages
There are many different programming languages to choose from.
Each language has its own set of very strict language rules.
C# is one such programming language.
Other languages include Java, C++, Visual Basic, Python, JavaScript, COBOL, Swift, Objective-C, Ruby, and Go.
Programming languages such as C#, Java, C++, and Visual Basic are high-level languages, since they have a high correlation with a spoken and written language.
Assembly language is a low-level language, as it has a low correlation with a spoken and written language and is more like the language the computer can understand.
Every computer program will need to be “translated” into “machine code” that the computer can understand, for example, byte code, object code, and binary code.
The process of “translation” is carried out by compilers, interpreters, or assemblers.
A Computer Program: A Recipe
A recipe for fifteens
Ingredients | Instructions |
---|---|
15 digestive biscuits 15 marshmallows 15 glacé cherries, cut into halves or smaller About 150 ml of condensed milk 100 g of desiccated coconut | Add 15 digestive biscuits to a bag and “smash” the biscuits with a rolling pin until they are fine crumbs. Place the crumbs in a mixing bowl. Slice the 15 marshmallows into pieces; we decide how big the marshmallows should be. Slice the 15 cherries in half or smaller; we decide how big the cherries should be. Add the cherries and marshmallows to the digestive biscuit crumbs in the mixing bowl. Stir the mixture until the cherries and marshmallows are spread evenly around the biscuit crumbs. Pour the 150 ml of condensed milk on top of the biscuit, glacé cherry, and marshmallow mix. Mix the contents in the bowl and add more condensed milk if required, so that the mixture is not dry. Cut a large piece of tinfoil and spread half of the coconut onto the tinfoil. Scoop the wet biscuit, glacé cherry, and marshmallow mix onto the tinfoil and add the other half of the coconut to the mixture. Roll the tinfoil over the mixture to create a sausage shape. Move the rolled mixture to the fridge and leave in the fridge for 3 or 4 hours. Remove the roll from the fridge and cut it into 15 slices. |
A list of instructions, directions, written in a language – in this case it is English.
Likewise, a computer program contains a list of statements, directions, written in a programming language such as C#.
A list of ingredients . The ingredients are of various types, for example, biscuits, marshmallows, glacé cherries, condensed milk, and desiccated coconut.
Likewise, a computer program contains a list of variables, ingredients. The variables will be of various types, for example, numbers, text, Customer, and Policy.
The following two code examples show the structure of code for C# and Python. Even at this early stage, by looking at the code examples, we should see some similarities between the two different programming languages, C# and Python. By completing the chapters in this book, we will become more familiar with C# programming, and other programming languages will be less “daunting” to look at and to program with.
Listing 3-1 shows C# code, which will ask the user to input two values and then totals the values. The program is like our recipe; it is a set of instructions.
Sample C# program
Sample Python program
Type in C#
In C# we will often refer to the variables and their types. So, when we see the word type in relation to a variable, we need to say to ourselves type means a variable that has a particular type, for example, int, float, or char. A type indicates the data type of the variable, which will be stored, for example, bool, byte, sbyte, char, decimal, double, float, int, long, or short.
In C# all data is defined within a type. So we could have a type called Car and the data might include the odometer reading. The odometer reading might be of type int and we would say that the odometer type is int and it is contained within a Car type.
For now, we just need to understand we will have variables in our C# code and they will have a type. We will get more information and knowledge of types as we progress through the chapters and topics. C# is a strongly typed programming language and this means the type of a variable cannot be changed once it has been declared. This is not the same principle in some other programming languages.
Built-in types, also called predefined or primitive data types, which include the ones we previously mentioned, for example, bool, byte, sbyte, char, decimal, double, float, int, long, and short.
User-defined types, which we as developers create because we wish to have our own custom types. We said earlier that the odometer type could be int and it could be contained within a Car type. But we should think, Where did the Car type come from? Well, the answer is we would have to create it. C# does not provide us with a primitive or predefined type called Car. When building applications, we may wish to have types like Car, Customer, Policy, Agent, Claim, etc. This will be covered when we meet Chapter 13.
When we write a C# program, we are linked to .NET, and we can avail of what is called the Common Type System (CTS) . Think about professional programmers in companies throughout the world who use a variety of programming languages. Within a company there may be a team of developers building an application using Visual Studio, but some developers are writing their code using C#, while others are writing their code using VB.NET and each language has its own data types. So how will it work when they wish to put the application together and have the C# parts communicate with the VB.NET parts. Well, that is one of the benefits of .NET and its Common Type System as it takes control and ensures that the different types from the individual languages are compiled to a common data type.
- 1.
Value type
Value type variables directly contain their values. The value types handled by the Common Type System arePrimitives, for example, bool, byte, sbyte, char, decimal, double, float, int, long, and short
Enumerations, which are used to assign constant names to a group of integer values, as in Listing 3-3
Example of an enumeration
Example of an enumeration with the default values overwritten
Example of an enumeration with default values assigned
Structure (struct), which is used to store data
Example of a struct
Another example of a struct
- 2.
Reference type
When we talk about a reference type, we mean we are not dealing with the actual value, the real data, but we are dealing with a reference to the data held in memory. The reference types handled by the Common Type System areRoot, for example, Object
String, for example, string policyType;
Arrays, for example, string[] repairShopClaims = new string[8];
Classes
Listing 3-8 shows an example of a class called Policy.
Example of a class
Interfaces
Delegates
We should not be concerned about these Common Type System types, for now. It is just important that we realize there are different types within C# and the Common Type System of .NET. As we progress through the chapters, we will gain more knowledge of the types, and more importantly we will consistently use them in all our coding examples.
The Basic Operations of a Computer
Basic operations of a computer
Input | The computer can accept user input from the keyboard. |
Process | The computer can perform arithmetic calculations and other types of processing. |
Output | The computer can display a message or a result on the screen or some other output source. |
Combination | The computer can combine these operations in three ways: Sequentially – A sequence of operations is performed one after the other. Repeatedly – A sequence of operations is performed a number of times. Selectively – One, two, or more sequences of operations are performed depending upon a condition, for example, is counter <2. |
Subprograms | A program can contain a number of smaller programs. We can for now call a subprogram a method or a function . |
C# Program Application Formats
Every programming language will have a structure that we need to understand and abide by if we wish to write code using that language. In the C# programming language , there are basic elements that all C# programs must have, and these basic elements depend on which format of application we are developing. In this book we will be concentrating on writing code for console applications, and as we go through the chapters in the book, we will gain more understanding of console applications. Using C#, we can write applications for different formats, three of which are discussed in the following.
Format 1: Console Application
We can think of the console as a two-tone screen like the black and white screen in the top section of Figure 3-2, although it can be changed, as shown in the lower section of Figure 3-2. The console is where input from the user is accepted and output from the computer program is displayed. Nowadays, while Windows and web-based applications are the predominant application formats for C#, console applications are still used to perform many tasks, which are not dependent on a “pretty” user interface (UI) .
We will be using an Integrated Development Environment (IDE) called Visual Studio Community Edition , and when we write our C# code in the editor of Visual Studio, we will need to run it to make sure it works properly. Our C# console application will run in a console window, which may have a black background and white text or some other combination of colors.
In learning to program, it is very important that we understand the programming concepts and forget about user interface design. The interface design can be built into the applications that we create, after learning all the core programming concepts. In reality we need to concentrate on ensuring that our code is well designed, has no errors or bugs, and works as required. There would be no point in having code that did not work properly, and there would be absolutely no point in having a well-designed, “pretty” user interface that was not functioning as expected because the code behind it was not working correctly.
Format 2: .NET MAUI
Format 3: ASP.NET Web Applications
ASP.NET is a free web framework, created by Microsoft, to allow us to build modern web apps and services with .NET and C#. With ASP.NET we can use C# alongside HTML, CSS, and JavaScript allowing us to develop dynamic web pages, the “front end” of our application. For the “back end” of our application, we can use C# with ASP.NET to develop code for our business logic and that can interact with databases.
The Structure of a C# Program
General syntax and format for a C# program
The 11 lines of code shown in Listing 3-9 represent what has been a “typical” starting point for a new console application when using Visual Studio. Interestingly, from all the lines of code, only one of them contains executable code, Console.ReadLine().
Top-level statements, two lines
Delete them when the code appears and add our own code, which we will do throughout the chapters in the book.
Switch them off when we are creating the project, as in Figure 3-6.
We will delete the top-level statements when they appear so we are reinforcing the fact that “under the hood” of these top-level statements there is code. When we are starting to learn C# code, it is good to see what the “real” code looks like, not the cut-down version. As we become experienced, it will be fine to use the top-level statements and indeed it would be expected that as developers we would do so. It is also important to understand that top-level statements can only be used in one source file in our project application, and we will be creating more than one file in our projects. If we tried to use top-level statements in more than one file in the project application, the compiler would give us an error.
Code Analysis
This analysis of the code in Listing 3-9 will help us fully understand the basic form of the C# console application code.
All code is enclosed within a namespace. In this example our namespace is called ConsoleVersion1. The name starts with the line
Essentially, a namespace is like a folder, an area to store classes, the code. Namespaces provide us as developers with a way to keep one set of names separate from another. The class names declared in one namespace do not conflict with the same class names declared in another.
Understand that we cannot create a new Word document and save it with the same name in the same folder as the CSharpNotes.docx document, as this would cause the operating system to ask us if we wanted to replace, overwrite, the existing file.
On the other hand, if we save the file with the same name but in a different folder, this will be fine.
The reason for this is that the folders allow us to keep files separate from one another and the actual name of the file will include the folder name.
Examples
C:GerryDocumentsMyNotesCSharpNotes.docx
C:GerryDocumentsMyClassNotesCSharpNotes.docx
Below the namespace name is the opening curly brace, which is matched by the closing curly brace at the end. Therefore, all code is wrapped within the namespace braces. So the namespace code looks like Listing 3-11.
Namespace syntax
Opening and closing braces are widely used to contain blocks of code and segregate the blocks of code from each other.
Namespaces are therefore used in C# to avoid name conflicts and to control the access to classes and so on. With namespaces it makes it easier to locate related classes that hold our code, and they provide a structure for projects, which, in a commercial application, could contain hundreds of classes and other files. This is what we read earlier when we said .NET contains many libraries of code that are useful to us when we write our code.
The C# code is wrapped within the namespace but it must also then be written or contained within a class. In this example our class is called Program. So the class looks like Listing 3-12.
Class syntax
Below the class name is the opening curly brace, which is matched by the closing curly brace, just above the namespace closing brace. Therefore, our code is wrapped within the class braces.
The main entry point of our console application will be the method called Main. A method is simply a number of lines of code, a block of code. Later in this book, we will look at methods in detail.
Our lines of code for the Main() method are enclosed between the opening curly brace and the closing curly brace. So the Main() method looks like Listing 3-13.
Main() method syntax
static – Later in the book when we look at classes and methods in detail, we will become familiar with the use of the keyword static. For now, just forget about static and simply accept its use in the code as shown.
void – This means that when all the lines of code within a method are executed, no value will be returned from the method – it is a void return. We will see more about this later in the book when we look at methods in detail.
string[] – We will see more about this later in the book when we look at arrays in detail. Essentially, it means that the Main() method can accept, be given, input values that are of type string. The [] means that it is an array of strings, one or more string values. So the Main() method can accept a number of values, variables, of type string.
args – args is the name of the string array. If we change the name from args to something else, it will not affect the running of the program. In Figure 3-7, args has been amended to gerry and the program has been run. The result is the same as that shown earlier, the only difference being the name of the array.
It should be noted that not all our code will be written inside the Main() method or indeed any method, but it will be written within a class, which is always contained within a namespace.
Namespaces
As we have read earlier, a console application is contained within a namespace. A namespace may be thought of as a storage area for some classes, which themselves contain methods. Microsoft has written thousands of base classes and stored them in namespaces. When we write our C# code, we will create many more classes and we must follow the same practices as Microsoft and store our classes within our own namespaces. Storing our classes in namespaces makes code more manageable and easier to maintain.
The using keyword for importing namespaces
Classes
As stated earlier a console application is contained within a namespace and within the namespace there will be a class or classes . A class is used to allow us to create our own types using C# code. A class is like an outline that will let us define the type we want, using other types, methods, and variables. In the example code, Listing 3-14, we have a class called Program. As we become more proficient in our C# coding, we will begin to develop our own more complex classes.
- A class for the type Pizza, to define that all pizzas have
A pizza base
A pizza sauce
Toppings
- A class for the type InsuranceQuote to define that all quotes must have
An applicant's forename
An applicant's surname
An applicant's date of birth
A method to calculate the insurance premium
Once we define the blueprint class for InsuranceQuote , we will be able to use the class to create specific types of InsuranceQuote. For example, we can create a CarInsuranceQuote or a HomeInsuranceQuote. The two classes, CarInsuranceQuote and HomeInsuranceQuote, are called instances of the class, and each instance will contain an applicant's forename, an applicant's surname, an applicant's date of birth, and a method to calculate the insurance premium.
What we should be clear about is that by the time we start Chapter 13 on classes and objects, which is a complex topic, we will be well prepared and should find the complex topic more manageable.
A class exists inside a namespace.
A class can contain variables, for example, forename, surname, and dateofbirth.
A class can contain methods, for example, CalculateInsurancePremium().
The term instance has been used to describe our copy of the class. More importantly it is possible to say our “copy” is an object. We will study classes and objects in more detail in a future chapter.
As we go through the course chapters, we will be reminded of the fact that a class contains methods and variables. This is a key concept and will be relevant when programming all the code examples. We will also see later that, instead of saying variable, we will say property or field or member when we talk about them in classes, but in our learning just think variables.
variable forename
variable surname
variable dateofbirth
method CalculateInsurancePremium()
Notice that a variable has a name that we give to it. It is one word.
Notice that a method has a name that we give to it followed by the open bracket, followed by the close bracket, that is, ().
Main() method has open and close brackets ()
The Main() method is interesting because it accepts an input. As developers we can code any method to accept input. Alternatively, we can code a method so it does not accept a value or values.
Naming a Class: Class Identifiers
camelCase – Where the first letter of the first word in an identifier is lowercase and the first letter of all other words are uppercase, for example, carInsurance
PascalCase – Where the first letter of each word in an identifier is uppercase, for example, CarInsurance
When naming a class, we should use a noun phrase.
The class name should describe what the class does; make the name descriptive.
Use the singular rather than the plural, for example, use Agent rather than Agents.
Start the class name with a capital letter.
Keep the class name and the filename the same. This is not always required, but it would be seen as the norm and makes for consistent naming across all classes.
Use PascalCase, which means every word in the class name starts with a capital letter. This is better than using underscores, as in Table 3-3.
The class name could begin with an @ symbol, which would also allow us to use C# keywords as the class name, but maybe not a good idea!
Valid and invalid class identifiers
Valid class identifier | Invalid class identifier |
---|---|
Program | Program Version 1 |
Customer | 1Customer |
Student | %Student |
Author | *Author |
@double (but don't use it) | double |
Bank_Account | Bank Account |
Customer_Order | Customer Order |
Mailing-List-For-Customers | Mailing List For Customers |
Student~Results~For~Test | Student Results For Test |
Car_Insurance_Quote | -Car-Insurance-Quote |
When we are learning to code, using naming conventions can be helpful, but do not obsess over them. The important thing is to get to understand and program in the C# language.
Chapter Summary
A computer program is a set of instructions created by a programmer.
A computer program is like a cooking or baking recipe.
The computer can perform input, process, and output using the program.
C# programs can be used in writing console applications, .NET MAUI mobile applications, ASP.NET web applications, and many other types.
There is a structure to all C# programs, which includes the use of namespaces, classes, and methods, including the Main() method.
The keyword using is used with a namespace to “import” another namespace.
Classes contain variables (properties, fields, members) and methods.
Methods always have the () after them, for example, Main().
In finishing this chapter and increasing our knowledge, we are advancing to our target.