Learn C#

The Easy Way. Through Examples


Textbook, 2018
309 Pages, Grade: 14

Excerpt

Contents

Chapter 1 Introducing C#
1.1 Visual C#.NET
1.2 VisualStudio.NET
1.3The ·NET Framework
1.4 System Requirements
1.5 Visual Studio.NET IDE
1.6 Console Application.
1.7 Windows/Forms Application.
1.8 Editing, Compiling & Executing c# Programs.
1.9 Parts of A c# Program
Exercise

Chapter 2 Object-Oriented Concepts
2.1 Classes & Objects
2.2 Class Hierarchy & Inheritance
2.3 Accessibility of Class Members
2.4 Constructors &Destructors
2.5 Polymorphism
2.6 Interfaces
2.7 Obj ect Interaction
2.8 Coding for Objects.
Exercise

Chapter 3 c# Basics
3.1 Data Types
3.2 Identifiers
3.3 Variables, Constants, and Literals
3.4 Declaring Variables and Constants
3.5 Operators and Expressions
3.6 Assignment Statements
3.7 Type Casting & Boxing/Unboxing
3.8 Checking and Unchecking
3.9 Input/Output Statements
3.10 Namespaces
Exercise

Chapter 4 Program Control Structures
4.1Controlling Program Execution
4.2 Sequence Structure
4.3 Selection Structure
4.4 Loop/Repetition Structure
4.5 Other Branching Commands
4.6 Infinite Loops
Exercise

Chapter 5 Built-in Methods
5.1 Built-in Methods
5.2 Mathematical Methods
5.3 Random Number Generators
5.4 String Methods
5.5 Data Conversion Methods
5.6 Character Methods
5.7 Date/Time Methods
5.8 Format Methods
5.9 Sample Programs
Exercise

Chapter 6 Programmer-defined Methods
6.1 Why Programmer-defined Methods
6.2 Defining Methods
6.3 Calling Methods
6.4 Passing Arguments to Methods
6.5 Method Types & Return Values
6.6 Recursive Methods
6.7 Delegates
Exercise

Chapter 7 Arrays
7.1 Why Arrays
7.2 One-Dimensional Arrays
7.3 Two-Dimensional Arrays
7.4 Multi-Dimensional Arrays
7.5 Jagged Arrays
7.6 Collections
7.7 Sample Programs
Exercise

Chapter 8 Structures
8.1 What are Structures
8.2 Structure Declaration
8.3 Nested Structures
8.4 Arrays of Structures
8.5 Sample Programs
Exercise

Chapter 9 Exceptions
9.1 What is an Exception
9.2 Exception Classes
9.3 Exception Handling
Exercise

Chapter 10 Text Files
10.1 Input/Output
10.2 File Streams
10.3 Classes for Input/Output
10.4 Reading Data from Text Files
10.5 Writing Output to Text Files
10.6 Sample Programs
Exercise

Chapter 11 Accessing Databases
11.1 Database Concepts
11.2 What is ADO.NET
11.3 Creating Microsoft Access Database
11.4 Basic SQL Commands
11.5 Aggregate Functions
Exercise

Chapter 12 Object-Oriented Programming
12.1 What is OOP .
12.2 Classes and Objects
12.3 Static & Instance Class Members
12.4 Class Inheritance
12.5 Constructors & Destructors
12.6 Abstract Classes
12.7 Interfaces
12.8 Object Interaction
Exercise

References

Preface

Visual C# 2015, one of the components of Visual Studio 2015, is one of the most powerful, versatile and modem object-oriented programming languages available today. Developed by Microsoft, it combines all the best features available in programming languages.

c# provides a rich repertoire of library/built-in functions that allow programmers to develop all kinds of applications with relative ease - be it Console, Windows/Forms, Web or Mobile Applications.

This book is intended for beginners as well as those with some programming knowledge. It is suitable for those students who are pursuing a course in Computer Science, Software Engineering, Information Technology, Management Information Systems, Engineering and Mathematics. It starts with the basics, and gradually progresses to more advanced topics such as arrays, stmctures, classes, text files and databases. So whether you are a beginner or intermediate programmer, this book will help you master the essentials of c# very quickly. The book is written in a simple, easy-to-read style and contains numerous examples to illustrate the concepts presented. It also contains exercises at the end of each chapter to test your grasp of the subject matter.

Acknowledgements

I would like to gratefully acknowledge the contributions of several people who have in one or another assisted me in the preparation of tilis book. I would like to thank all my IT students and colleagues for their valuable input and feedback in the preparation of this manuscript.

My grateful thanks also go to Professor Dr. Premkumar Rajagopal, President of the Malaysia University of Science and Technology for giving me the opportunity, freedom, encouragement and support that I needed in the preparation of this manuscript. I would like to especially thank him for creating and nurturing an environment that actively promotes learning, research, teamwork and personal development. His dynamic leadership is greatly appreciated.

Last but first I would like to thank God for giving me the desire, motivation, interest, passion, strength and guidance to successfully complete this manuscript.

Dr. p. Sellappan

Professor of Information Technology

Dean of School of Science and Engineering

Provost of Malaysia University of Science and Technology

About the Author

Dr. P. Sellappan is currently Professor of Information Technology, Dean of School of Science and Engineering, and Provost of the Malaysia University of Science and Technology. Prior to joining Malaysia University of Science and Technology, he held a similar academic position in the Faculty of Computer Science and Information Technology, University of Malaya, Malaysia.

He holds a Bachelor in Economics degree with a Statistics major from the University of Malaya, a Master in Computer Science from the University of London (UK), and a PhD in Interdisciplinary Information Science from the University of Pittsburgh (USA).

Working in the academia for more than 30 years, he has taught a wide range of courses both at undergraduate and postgraduate levels: Principles of Programming, Advanced Programming, Programming Languages, Data Structures and Algorithms, System Analysis and Design, Software Engineering, Human Computer Interaction, Database Systems, Data Mining, Health Informatics, Web Applications, E-Commerce, Operating Systems, Management Information Systems, Research Methods, Mathematics and Statistics.

Professor Sellappan is an active researcher. He has received several national research grants from the Ministry of Science and Technology and Innovation under E-Science and FRGS to undertake IT-related research projects. Arising from these projects, he has published numerous research papers in reputable international journals and conference proceedings. Besides, he has also authored over a dozen college- and university-level IT text books.

As a thesis supervisor, he has supervised more than 70 Master and PhD theses. He also serves in editorial/review boards of several international journals and conferences. He is also chief editor of the Journal of Advanced Applied Sciences and the Plain Truth magazine. He is a certified trainer, external examiner, moderator and program assessor for IT programs for several local and international universities.

Together with other international experts, he has also served as an IT Consultant for several local and international agencies such as the Asian Development Bank, the United Nations Development Program, the World Bank, and the Government of Malaysia. His professional affiliation includes membership in the Chartered Engineering Council (UK), the British Computer Society (UK), the Institute of Statisticians (UK), and the Malaysian National Computer Confederation (MNCC).

Chapter 1 Introducing C#

Learning Outcomes:

After completing this chapter, the student will be able to

- Describe the Visual Studio 2015 Integrated Development Environment.
- Differentiate between Console and Windows Applications.
- Explain the different parts of a c# program.
- Edit, compile and run c# programs.

1.1 Visual C#.Net

Microsoft’s Vismi c# 2015 is one of the most popular general-purpose object-oriented programming languages. It’s powerful, versatile and relatively easy to use. You can use it to develop a wide range of applications that run on the .NET Framework. It comes with a rich repertoire of built-in functions/methods which programmers can use to develop Console, Windows/Forms, Web and Mobile Applications, distributed components, client-server applications, and more, ft comes with an advanced code editor, interface designer, integrated debugger and other tools for easy coding and testing.

Using c# lias many benefits:

- It is relatively easy to use. Editing, compiling, running and debugging c# programs using the Integrated Development Enviromnent (IDE) is easy.
- It is powerful and versatile.
- It can be used to develop Console, Widows/Forms, Web and Mobile Applications.
- It is object-oriented. Programmers have all the benefits of the object-oriented paradigm such as modularity, inheritance, polymorphism and software reuse.
- It is robust, meaning, it can handle all types of situations - both expected and unexpected. Tilis helps us to minimize errors in programs.
- Modules are linked dynamically (at run-time). Only modules that are needed are linked. Tilis reduces program size, saves memory, and executes faster.
- ft uses the Language-Integrated Query (LINQ) to provide built-in query capabilities across a variety of data sources.
- It provides a rich repertoire of built-in/library functions that helps programmers to simplify programming and speed up the software development process.

1.2 Visual Studio.NET

Visual Studio.NET 2015 provides an Integrated Development Enviromnent (IDE) for creating impressive applications for Console, Windows/Forms and Web and Mobile Applications, and Cloud services. It provides rich tools and services to candle projects of any size and complexity. (It comes with Visual c#. Visual Basic, c++, F#, Python, HTML/JavaScnpt, Node.js etc.)

1.3 The .NET Framework

The .NET Framework is Microsoft’s computing platform created to simplify application development, especially for the Internet, ft is a general-purpose development platform for developing any kind of application. It provides key capabilities for building high quality applications including automatic memory management and support for modern programming languages. With it, you can develop any application for the Microsoft platform. It comes with reusable libraries for building all types of applications. It also supports multiple programming languages.

The .NET Framework includes the following components:

Class Libraries

The .NET Framework comes with many predefined classes organized into different categories called namespaces. A namespace logically/semantically groups related functions. For example, one namespace may provide building blocks for developing Windows Applications; another, for Web Applications. Some of these may be further divided into more specific namespaces. For example, Web Development namespace may contain a namespace for developing Web Services.

The Runtime

The .NET Framework provides Runtime components including the following:

Common Language Specification (CLS): Tilis component ensures that code written in different languages all behave in a uniform way such as when an object is instantiated or when a method is invoked with a value or reference parameter. Tilis is important in the .NET enviromnent as code written in different languages (e.g., c#, C++, VB, JScript) may behave differently.

Common Type System (CTS): Tilis component defines the basic data types such as Integer, Double and String. It facilitates interoperability between languages that use the .NET Framework, ft makes cross­language compatibility possible. (In the .NET Framework, you can use multiple programming languages to develop an application.)

Common Language Runtime (CLR) : Tilis component manages the execution of all applications developed using the .NET library.

Figure 1.1 illustrates the cross-language operability via the Coimnon Type System and the Coimnon Language Runtime.

Abbildung in dieser Leseprobe nicht enthalten

Figure 1.1 Cross-language operability

Garbage Collector (GC) is a memory manager whose job is to reclaim memory allocated to objects that are no longer needed such as when an object is deleted.

Just-in-Time (JIT) Compiler compiles the intermediate language (IL) to native code specific to the target machine and operating system. The IL code is compiled only when needed.

The compilation of a c# program from source code to intermediate code and to native machine code is shown in F igure 1.2.

Abbildung in dieser Leseprobe nicht enthalten

Figure 1.2: Stages of compilation of a c# program

1.4 System Requirements

The recommended system requirements for running c# programs are:

- 1.6 GHz or faster processor
- 1.5 GB of RAM
- 10 GB of available hard disk space
- 5400 RPM hard disk drive
- DirectX 9-capable video card that runs at 1024 X 768 or higher display resolution
- CD-ROM drive
- Windows XP/Vista/7/8

1.5 Visual Studio.NET IDE

When you launch Microsoft Visual Studio 2015, you will see the Integrated Development Environment (IDE) shown in Figure 1.3.

The IDE has several parts:

Title bar with the title Start Page - Microsoft Visual Studio

Menu bar with several menu items such as File, Edit, View, Debug, Team, Tools, Test, Analyze, Windows, and Help. When you click on a menu item, you will see a pull-dow n menu giving several options. The pull­down menus for some of the menu items are shown in Figure 1.4. Some of the options in the pull-dow n menu have Shortcut keys. For example, the Shortcut key for New File (in File menu) is Ctrl+N and the Shortcut key for Properties Window (in View menu) is F4. You can use the Shortcut keys from anywhere on the screen without selecting a menu item.

Main Window displays the introductory “Start Page” when the Visual Studio is launched. Tilis window is tabbed such that you can switch between several files with ease by clicking on their filenames.

Server Explorer and Toolbox controls appear whenever they are clicked and provide various additional capabilities such as access to user interface building blocks for Windows and Mobile applications.

Solution Explorer Window displays information about the current project.

Properties Window gives you a detailed view of the contents of the current project and allows you to perform additional configuration of individual elements.

Start Options provide you options such as New Project, open Project, open from Source Control, and a list of recently opened projects to start or load.

Output Window displays the output when a project is compiled or executed.

The Standard Tool bar located just below the Menu bar has several icons. These icons represent some of the commonly used functions such as opening a new or existing file, saving the current file, пали gating backward or forward, undo and redo previous operation. These icons represent only a subset of the functions. To use other functions not ал/ailable on the Standard Toolbar, you must click the appropriate menu item and select the desired function.

The Minimize, Maximize and Close buttons perform the same functions as in other Windows based applications. Clicking the Minimize button puts the application on the Taskbar. To activate, click the icon on the Taskbar. Clicking the Maximize button causes the application to fill the entire screen and clicking it again will cause it to гел/ert to its original size. Clicking the Close button closes the application.

Note that some of the options in the pull-down menus in Figure 1.4 are grayed out. That means they are not ал/айable/applicable for use in the current context. Thus it minimizes inadvertent errors.

Abbildung in dieser Leseprobe nicht enthalten

Figure 1.3: Visual Studio 2015 IDE

Abbildung in dieser Leseprobe nicht enthalten

Figure 1.4: c# Menus

1.6 Console Application

To create and run a c# Console application, use the following steps:

1. Start Visual Studio, on the menu bar. Select File > New > Project

Abbildung in dieser Leseprobe nicht enthalten

2. Expand Installed, expand Templates, expand Visual c#, then select Console Application.

Abbildung in dieser Leseprobe nicht enthalten

3. In the Name box, give a name for your project, then click the OK button.

4. Once the project is initialized, you will see the below code in the Code window. We llave added the highlightedtwo lines of code to make the program display “Hello World!”

Abbildung in dieser Leseprobe nicht enthalten

5. Select the F5 key or click * start * button to run the project. A Command Prompt window will appear with the message Hello World ! like the one shown below.

Abbildung in dieser Leseprobe nicht enthalten

6. Press any key to exit from the application.

1.7 Windows/Forms Application

To create and run a c# Windows application to display “Hello World!” message, use the following steps: 1. Start Visual Studio, on the menu bar. Select File > New > Project

Abbildung in dieser Leseprobe nicht enthalten

2. Expand Installed, expand Templates, expand Visual c#, then select Windows Forms Application.

Abbildung in dieser Leseprobe nicht enthalten

3. In the Name box, specify a name for your project, then click the OK button.

4. Once the project is initialized, move the mouse pointer to the Toolbox bar on the left of the screen. Select All Windows Forms and double click on the Button, Label, and TextBox icons to add them to the

main form of the application. Select the Form and change the text accordingly under the Properties window. Do the same for Label, and Button controls.

Abbildung in dieser Leseprobe nicht enthalten

Abbildung in dieser Leseprobe nicht enthalten

5. To add code for the button, double click on the button that you just added to the form.

6. You will see some lines of code. Go to the buttonl Click method and add the highlighted code shown below.

Abbildung in dieser Leseprobe nicht enthalten

7. Select the F5 key or click * Ítart ' button to run the project. Enter “Hello World!” inside the Textbox.

8. Click on Display button and the program will output “Hello World!” in a message box as shown below.

Abbildung in dieser Leseprobe nicht enthalten

1.8 Editing, Compiling& Running c# Programs

Let’s illustrate these steps for compiling and executing a simple c# Console application to display a greeting message.

1. Start Visual Studio. On the menu bar, select

File > New > Project >Expand Installed>Expand Templates > Expand visual C#>Console Application

2. Type the highlighted code (without the line numbers) in the Code window.

Abbildung in dieser Leseprobe nicht enthalten

Select the F5 key or click * Ítart ' that looks like the one shown below.

Abbildung in dieser Leseprobe nicht enthalten

Note that the program is compiled automatically when you run it. So you don’t have to explicitly compile the program.

1.9 Parts of a c# Program

Let’s briefly explain the various parts of a c# program.

Comments

Comments are inserted into a program to make it more readable. Coimnents can appear anywhere in the program. Coimnents are not executable statements; the compiler simply ignores them.

Comments can span several lines (lines 1 to 3 in the code) or a single line (line 4). A multi-line comment start with the characters /* and ends with the characters */. The pair of characters (/* and */) must appear together (with no space) as c# treats them as a single symbol.

A single line comment starts with two forward slashes (//). Everything on that line after the slashes is treated as a coimnent. It can appear on a single line (line 20) or after a statement (line 17).

Line spacing

Blank lines can be inserted in a program between statements to make it more readable. For example, we llave inserted a blank line between lines 3 and 4. Blank lines are useful for separating methods, to begin a separate task, or to begin and end a lengthy loop.

Namespace

A namespace is a collection of related classes, c# provides many namespaces to simplify programming. The basic namespaces that c# programs require are System, System. Collections . Generic and System. Text. To use them, you must prefix them with the keyword using (lines 5-7). Note that there is a semicolon ( ; ) at the end of each namespace directive. The semicolon terminates the statement. Tilis is the basic rule for all executable statements unless they appear in a block enclosed between a pair of curly braces ({}).

The above namespaces provide the basic classes that all c# programs require. For example, the System namespace provides the class Console for reading input data from the Keyboard and for displaying output on the Screen. Tilis class contains methods such as ReadLine ( ) (lines 19 and 22), Write ( ) (line 18), and WriteLine( )(line 21).

Keywords

Keywords (also called reserved words) have special meaning in c#. So they must only be used for their intended purpose. You cannot use them for any other purpose. For example, in the above code, using and System (line 5) are keywords.

Case sensitivity

c# syntax is case-sensitive, c# treats uppercase and lowercase letters as different characters. So you must be careful when naming namespaces, functions and variables. For example, if you had typed the word system instead of System in line 5, the compiler will give you an error message. Similarly, the variables name, Name and NAME are all different.

Class

c# is an object-oriented language. Every c# program must have at least one class.The above program lias one class: MyClass (line 12). It is prefixed with the keyword class. You can give your own class name - one that is meaningful. The body of a class is enclosed between a pair of braces ( {} ) (lines 13 to 24).

Main ( ) method

A c# program must llave the Main ( ) method (line 15). Besides tilis, it can also llave other methods. The body of each method must be enclosed between a pair of curly braces ( { } ) (lines 16 to 23).

Program execution will always start and end at Main ( ). The keywords public, static and void before Main ( ) have certain meanings:

public - Specifies that Main() can be accessed from anywhere such as from another class another class or another project.

static - Specifies that Main() is attached to the class (My c 1 a s s in tilis case) and not to an instance of that class.

void - Specifies that Main ( ) does not return any value to the calling program (operating system in tilis case).

You will need the above keywords when writing the Main ( ) method. (There are also other keywords which you will learn later in other chapters.)

Parameters

The curved brackets ( ) following Main is used to specify the parameter(s) that it needs. The above program doesn’t require any parameters, so there are no parameters enclosed in the brackets. But the brackets are still required even if a method has no parameters.

Variable declaration

Line 17 declares a variable called name of type string. The string is a keyword used to declare string variables. A string variable consists of a set of alphanumeric characters (letters, digits and underscores).

A variable is used to reference a memory location where you can store a data item such as the name of a person. A variable must begin with a letter and may be followed by one or more letters, digits and/or underscores (_). Special characters such as @, %, *, &, $ are not allowed in a variable. Blanks are also not allowed. A variable may be of any length from 1 to 255 characters. However, in practice, a variable seldom exceeds 25 characters. You must give meaningful names for your variables to make your program readable.

Input Statement

Input Statements allow you to read data from the Console (Keyboard). In the above program, the statement (line 19)

name = Console.ReadLine();

reads data írom the Keyboard, then assigns it to the variable name. The ReadLine ( ) method on the right- hand side of the assignment operator = is part of the Console class.

Assignment statement

An assignment statement has a variable on the left-hand side, the assignment operator =, and an expression on the right-hand side. In an assigmnent statement, the value of the expression on the right-hand side of the assignment operator is evaluated and the restìi is stored in the variable on the left-hand side. The expression can be a number, a literal, a variable, an algebraic expression or a method call that returns a value. In tilis case, the method reads a line of text entered from the keyboard.

Output statement

Output statements are used to send output to the Console (Monitor/Screen). The above program has two output statements (lines 18 and 21). The statement

Console.Write("Enter you name: ");

displays a message/prompt on the screen asking the user to enter a name. The Write method (which is part of the Console class) displays the message enclosed between the pair of double quotes ("). After the statement is executed, the cursor will appear on the same line immediately after the prompt.

The statement (line 21)

Console.WriteLine("Good day, " + name);

is similar to the previous one but it will move the cursor to the next line after displaying the message Good day, followed by the name. The + operator acts as a concatenation (join) operator, ft joins the message and the name. For example, if the name entered is Sellappan, the program will display

Good day, Sellappan

Note: Don’t worry if you haven’t fully grasped the material presented in tilis chapter. The purpose in tilis chapter is to introduce you to the c# programming language. The sample code is intended to give you an idea how a c# program looks like. As you progress to the next few chapters you will be able to write simple c# programs.

Exercise

1. Explore Visual Studio 2015 ’slntegrated Development Enviromnent to view some of its main features.

2. Click on each menu item on the Menu bar and explore the functions available.

3. Write a simple Console application using the steps given in the chapter.

4. Write a simple Windows/Forms application using the steps given in the chapter.

5. Explore c# debugging facilities.

Chapter 2

Object-Oriented Concepts

Learning Outcomes:

After completing this chapter, the student will be able to

- Explain classes and objects.
- Explain class hierarchy and inheritance.
- State the purpose of abstract classes and interfaces.
- Discuss the scope and access levels of class members.
- Discuss constructors and destructors.
- Explain polymorphism, method overloading and method overriding.
- Discuss object interaction.

2.1 Classes & Objects

As c# is an object-oriented language, you need to be familiar with object-oriented concepts before you can write c# programs. These concepts include classes and objects, encapsulation, class hierarchy and inheritance, abstract classes and interfaces, constructors and destructors, polymorphism, method overloading and method overriding, object interaction and message passing.

A class is a template for creating objects. All objects from the class llave the same attributes (variables) and methods (functions). The methods manipulate the variables. For example, all objects created from the Employee class will have attributes like employee number, name and salary, and functions like calculate salary ( ).

A class encapsulates (packages) both variables and methods. It is self-contained - the methods manipulate the data. The variables store the object’s data while the methods manipulate its data. The variables and methods are called class members.

An object is an instance of a class. You can create as many instances as you want for a class. For example, you can create objects like Miriam, Wong, Kamala and Susan for the Employee class as shown in Figure 2.1.

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.1: Class and its objects

A class is represented using a box diagram with three partitions. The top partition shows the class name; the middle, its variables; the bottom, its methods. Figure 2.2 shows the class Employee with its attributes and operations.

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.2: Class attributes and methods

Objects liave states. The state of an object is determined by the values of its variables. Changing the values of variables changes the state of the object. The methods in the class change the values of these variables.

Static & Instance Class Members

Ordinary variables of type int, double, string, etc. are allocated memory at compile time. The c# compiler knows exactly how much memory (in bytes) these variables require. These variables are allocated memory on the stack maintained by the c# system.

Object variables like Employee, student, etc. are allocated memory at run-time. The compiler doesn’t know in advance how much memory these variables require. The memory requirements for these variables depend on the program logic, c# allocates memory dynamically for these variables when they are created and frees the memory when they are deleted or no longer needed. Object variables are allocated memory on the heap (maintained by the c# system). Knowing the difference between stack and heap variables can help us write more efficient code - code that executes faster and uses less memory.

Variables in a class can be static or dynamic. The static variables are called class variables: they are attached to the class. Only one copy is maintained for all objects. The dynamic variables are called instance variables: they are attached to each instance.

Let’s illustrate: Assume company XYZ lias 1000 employees. As all employees llave the same company name (co_name), you need to store only one copy as shown in Figure 2.3.

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.3: All class instances share the static variable

2.2 Class Hierarchy & Inheritance

Related classes can be organized hierarchically. For example, the classes Person, student and Employee can be arranged hierarchically as shown in Figure 2.4. Here, Person is called the base, super or parent class and student and Employee are called derived, sub or child classes. Tilis is an example of a two-level hierarchy.

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.4: A two-level class hierarchy

Inheritance refers to a derived (sub) class inheriting the variables and methods of its base (super) class. The derived classes automatically inherit all the variables and methods of the base class. That means variables and methods declared/defined in the base class need not be declared/defined again in the derived classes.

Abbildung in dieser Leseprobe nicht enthalten

Let’s illustrate: Assume classes Person, student and Employee in Figure 2.4 have the following variables and methods.

Figure 2.5 shows the inherited members in the subclasses student and Employee. Thus Student inherits the variables Name, Age and Sex and the methods Initialize(), Add ( ) and Modify ( ) from the base class Person. In addition, it also lias its own variables StudNo and Course and its own method Changelnfo().

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.5: Inherited members from base class

A class hierarchy can have many levels. Figure 2.6 shows a three-level class hierarchy. Here, Local employee inherits all the members (variables and methods) of its base class Employee, as well as indirectly, all the members of the Per son class.

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.6: A three-level class hierarchy

Abstract Classes

Abstract classes cannot be instantiated, meaning, you cannot create instances of an abstract class. Abstract classes are used to specify variables and methods at a higher level. The classes that inherit the abstract class must implement these methods using the specified variables and methods.

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.7 illustrates abstract classes. The base class Patient declares the variable Patientid and the method Delete ( ). The derived classes Outpatient and InPatient then implement the Delete ( ) method using the variable Patientid. The Delete() method in InPatient and Outpatient overrides the Delete ( ) method in Patient.

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.7: Abstract classes

2.3 Accessibility of Class Members

Accessibility refers to the scope/visibility of class members (variables or methods). Access specifiers are used for tilis purpose. Access specifiers can be private, public, internal or protected. If the scope is private, the members can only be accessed from within that class; if the scope is publi c, they can be accessed from any class (including classes from other projects); if it is internal, it can only be accessed by any class in the current project; if it is protected, it can only be accessed by classes within the class hierarchy.

What tins means is: If you do not want another class to access members of a class, you declare them as private. If you want another class (including from other projects) to access its members, you declare them as public. If you want other classes in the current project to access its members, you declare them as internal. If you only want classes in a hierarchy to access its members, you declare them as protected.

By dc Га Lilt, all members of a class are private. In that case, the keyword private can be dropped altogether. In general, the scope of most variables would be private while the scope of most methods would be publi c. Public members are exposed to other classes; private members are not.

2.4 Constructors & Destructors

A constructor is a special method that is invoked automatically when an object is created. It lias the same name as the class. It is typically used for allocating memory when an object is created and/or for initializing variables, c# automatically provides a constructor for each class. You can also provide your own constructor(s). That means, a class will have one or more constructors.

A constructor can have zero or more parameters. A constructor can be overloaded, meaning, you can llave several constructors all having the same name but different number/type of parameters.

A destructor is also a special method that is invoked automatically when an object is deleted or goes out of scope. It also has the same name as the class but prefixed with a tilde (~). Destructors are typically used for freeing memory allocated to objects and/or for performing close-up operations such as displaying summary reports.

2.5 Polymorphism

Polymorphism means many forms. The term applies to methods that llave the same name in a class hierarchy but are implemented differently. A method is said to be polymorphic if it behaves differently in the base and the derived classes. Tilis feature allows two or more classes in a class hierarchy to use the same method name, but each class implements it differently.

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.8: Polymorphism

For example, in Figure 2.8, the class Shape uses the Draw ( ) method to draw a shape. The derived classes. Rectangle, Circle and Polygon, also uses the Draw() method, but they draw different shapes (rectangle, circle or polygon). So we say the Draw() method in Rectangle, Circle and Polygon overrides the Draw ( ) method in Shape.

Compile time polymorphism refers to binding overloaded methods at compile time. Tins process is called early binding. Overloaded methods have the same name but have different number and/or type of parameters. They behave differently depending on the number/type of parameters. (Note that method overloading is not the same as method overriding.)

Runtime polymorphism refers to binding methods that llave the same name in the base and derived classes. Tilis binding occurs at run-time and the process is called late binding. The methods in the derived classes override the method in the base class, thus stopping the inheritance.

2.6 Interfaces

A class must expose its services (methods) if it wants other classes to access them. That is, it must publish its services. Interfaces are used for tilis purpose. The interface (class) tells what services it provides to other classes. For example, if an Employee object wants to know the name of its department, it can send the EmpNo to a Dept object which can then access the department name and pass it to the Employee object.

Interfaces declare properties, methods and events (interface members). It is the responsibility of the inheriting classes to implement the methods. They are used to provide a standard structure for the inheriting classes.

Abstract classes can be used for the same purpose, but they are used mai nil when the number of members that need to be inherited is small. The classes that inherit the methods must implement them.

2.7 Object Interaction

In object-based systems, objects must interact to perform useful business functions. Objects interact by passing (sending) messages to one another. Passing messages is similar to calling methods and supplying parameters. The called object implements the method and passes the results to the calling object. Figure 2.9 illustrates the idea of message passing.

Abbildung in dieser Leseprobe nicht enthalten

Figure 2.9: Message passing

2.8 Coding for Objects

As c# is an object-oriented language, writing code is slightly different from writing code for procedure- oriented languages such as C/C++. To use an object, first create it using the class template. Then to access a variable/method, prefix it with a dot. The code below illustrates the idea.

Abbildung in dieser Leseprobe nicht enthalten

Exercise

1. Wltit are objects and how are they created?

2. List the inain benefits of class inheritance.

3. What is an abstract class? How is it useful?

4. What is an interface? How is it different from an abstract class?

5. What is the difference between method overloading and method overriding?

6. What is polymorphism and how is it useful?

7. Identify three classes for a library information system. For each class, list its variables and methods.

8. Write skeleton code to define class employee with variables name and salary and methods display name() and display salary() to display the name and salary.

9. How do objects interact with one another?

Chapter 3

c# Basics

Learning Outcomes:

After completing this chapter, the student will be able to

- Explain the different data types.
- Declare variables and constants.
- Use arithmetic, relational and Boolean operators.
- Form algebraic expressions.
- Write assignment statements.
- Write input/output statements.
- Explain the purpose of namespaces.
- Write simple c# programs.

3.1 Data Types

When you declare variables or constants you must specify their data types. The data type tells what type of data (integer, double, string. Boolean, etc.) will be stored in the computer’s memory. Some data types require more memory thill others, c# uses tilis information to allocate the correct amount of memory for the variables or constants.

c# supports several data types such as Boolean, byte, integer, long, float, double, character and string. The table below shows the various data types, their ranges, and the amount of memory (in bytes) needed to store them.

Abbildung in dieser Leseprobe nicht enthalten

You must choose the appropriate data type for your variables. For example, you can choose the short data type for small integer numbers (positive or negative), int for bigger integer numbers, and long for very large integer numbers. If you only need positive integers (for example, to store the population of a country), you can use the unsigned integer data type uint. For financial calculations, you can choose the decimal data type. For single characters, choose the char data type; for a string of characters, choose the string data type.

3.2 Identifiers

Identifiers are names used to represent variables, labels, class and object names, named constants and functions (methods). An identifier can be 1 to 255 characters long (although in practice it seldom exceeds 25 characters). It is formed by combining upper and/or lower case letters (A-Z, а-z), digits (0-9) and the underscore (_). Special characters such as @, #, *, ?, period (. ) and blank (white space) are not allowed in an identifier. An identifier always starts with a letter and may be followed by one or more letters, digits, or underscores.

Here are some examples of correct identifiers:

Correct Identifiers

Abbildung in dieser Leseprobe nicht enthalten

Here are some examples of incorrect identifiers:

Abbildung in dieser Leseprobe nicht enthalten

When forming identifiers, the following naming conventions are useful:

1. Use meaningful names. For example, you should use the variable name total (or sum) to store the total of a set of numbers instead of a variable name t ( or s).

2. If a variable is long, use mixed cases or underscores. For example, you can use the names TotalPay, Total_Pay or total_pay to store the total pay of all the employees in a company.

3. Prefix each identifier with a lowercase prefix to specify its data type. For example, you can use dblTotal instead of Total.

Note: Most programmers use lowercase letters (with underscore) to name variables.

Keywords

Keywords (or reserved words) are identifiers that llave special meaning in c#. So these keywords cannot be used as identifiers. That means you cannot use words such as Console, For, Switch, WriteLine and While as identifiers. The list of keywords in c# is given below.

Abbildung in dieser Leseprobe nicht enthalten

3.3 Variables, Constants and Literals

Variables are identifiers used to access data items stored in the computer’s memory. You can say they refer to memory locations. Each memory location can store a piece of data such as a character or a number. The value stored in a memory location can change during program execution As c# variables are case-sensitive, upper and lowercase letters are not the same. For example, the variables Total, total and totaL are not the same. They are three different variables.

Constants are similar to variables, but their values don’t change during program execution. For example, in a program that computes the area of a circle, radius would be a variable while pi (the value 3.142) w ould be a constant. To declare constants, you use the keyword const before the data type.

Literals are constant values assigned to variables. They can be numeric, character, string. Boolean or other data types.

The below are some examples of variables, constants and literals:

Abbildung in dieser Leseprobe nicht enthalten

There are also literals with specific meaning. They are called escape sequences or escape characters. These are especially useful for sending output to the console or printer. The table below gives a list of these escape sequences.

Abbildung in dieser Leseprobe nicht enthalten

Here are some examples:

// Print Hello world! on the next line Console.WriteLine("\nHello world !");

// Print Hello world! on the next tab position Console.WriteLine("\tHello world !");

// Print Hello world! on the next page Console.WriteLine("\fHello world !");

// Print Hi... and beep Console.WriteLine ("\aHi...") ;

// Print the character \

Console.WriteLine("\\");

3.4 Declaring Variables and Constants

To use a variable, you must first declare it. The declaration includes the name of the variable and its data type, e.g., int (integer), double, and string, c# will use tilis info nnation to allocate the correct amount of memory for the variable. Some data types require more memory than others. For example, a variable of type double would require 8 bytes whereas a variable of type int would require only 4 bytes.

Variable declaration in c# takes the general fonn:

type vari, var2, ..., varn;

where type refers to data type and vari to varn are the names of variables separated by a coimna. The semicolon tenninates the statement.

The following are some examples of variable declaration:

string Productcode; int Quantity; double Price; decimal Amount; float rate; char ch;

int x, y, z; // more than 1 variable of the same type on same line

double rate, salary

You can also initialize variables in a declaration statement as follows:

double total = 0.00; // declaring and initializing a variable

int n=20, m=5; char ch = 'a'; string name = "AAA"

Constants have fixed values, i.e., their values don’t cl binge during program execution. A constant is declared by using the keyword const followed by the type and name of the constant, the assignment operator and the value. It takes the general fonn:

const type var = value;

The following are some examples of constant declaration:

const double Rate = 7.50;

const decimal TotalPay = 99999999.99;

const int BufferSize = 1024;

const string Greetings = "Hello there";

const string Website = "http ://www.must.edu.my";

To distinguish between the different data types, programmers sometimes use certain conventions for naming variables and constants. They prefix them with 3 lowercase letters representing the data type. The following table shows the prefixes for several data types.

Abbildung in dieser Leseprobe nicht enthalten

The following are some examples of variable and constant declarations using the above convention:

string strProductCode; int intQuantity; const double dblRate = 7.50; bool blnMatch = true;

3.5 Operators and Expressions

Operators trigger some computation when applied to operands in an expression. There are several categories of operators: arithmetic, relational, logical, increment and decrement, and assigmnent operators.

Arithmetic Operators

The arithmetic operators are as follows.

Abbildung in dieser Leseprobe nicht enthalten

Here are some examples of arithmetic operations involving integer variables. If

a = 8, b = 3 and c = 2, then the expressions on the left column evaluate to the values on the right column. (Spaces may be inserted in an expression for readability.)

Note that there are no implied multiplication operations. That means you cannot write ab or (a) (b) or a. b to mean a times b. You have to write the multiplication operation explicitly as a*b.

Relational Operators

The relational operators are as follows:

Abbildung in dieser Leseprobe nicht enthalten

Abbildung in dieser Leseprobe nicht enthalten

Note tilat some operators such as <= and >= have two symbols, c# treats the two symbols as a single operator.

The restìi of a relational operation is always true or false. For example, if a = 3, b = 4 and c = 5, then the following holds:

Abbildung in dieser Leseprobe nicht enthalten

Boolean/Logical Operators

The Boolean or logical operators are as follows:

Abbildung in dieser Leseprobe nicht enthalten

Note: Although you can use the operators I (&) and II (&&) interchangeably for the logical OR (AND), there is a subtle difference. When you use the two character operators ( I I and &&), c# may not evaluate all the operands in an expression. For example, if X and y are Boolean, the expression X & y will yield false if X is false. It is not necessary to evaluate y. Tilis is not the case when you use the single character operator (I or &) where all the operands will be evaluated. Thus using I I and && will yield better performance.

The table below summarizes the results of the various logical operations for the Boolean variables X and y.

Abbildung in dieser Leseprobe nicht enthalten

The result of a logical operation is always true or false.

Here are some examples of logical expressions given X = true and y = false.

X I I y will yield true // same as X I y

X && y will yield false // same as X & y

!x will yield false

You can combine all the operators (arithmetic, relational and logical) in an expression as in the following examples, given a = 2, b = 3, ๐ = 4 and d = 5:

a < b II c < d will yield true

a > b && c > d will yield false

a + b >= d * c will yield false

Increment and Decrement Operators

c# also provides increment and decrement operators as shown in the table below.

Abbildung in dieser Leseprobe nicht enthalten

Here are some examples of increment and decrement operations, given a = 2, b = 3.

a++ will yield a=3 b++ will yield b=4 a-- will yield a=l b-- will yield b=2

Other Operators

c# also lias other operators as shown below.

Abbildung in dieser Leseprobe nicht enthalten

The is operator tests the data type of a variable. The ? : operator is a simple if... else conditional operator. The this operator references the current object.

Example 1

If i is of type int (integer) and X is of type double,

i is double will yield the value false X is double will yield the value true

Example 2

If sex is of type char and status is of type string, the statement status = (sex == 'M' ? "Mr״: "Ms");

will assign the string Mr to status if s ex is equal to M, otherwise it will assign Ms.

Example 3

If small, X and y are of type int, the statement

small = (x <= y ? X : y)

will assign the smaller of X and y to small.

Expressions

An expression can take the form of a constant, variable, computation, or fonnula. It can include blanks to make the code more readable. We have already seen the order of operator precedence in the previous examples. They follow the normal algebraic rules. For example, if an expression involves multiplication, division, addition and subtraction, the multiplication and division operations will be perfonned first before the addition and subtraction. When the operators llave the same precedence (example multiplication and division), evaluation always proceeds from left to right. You can use a pair of parentheses ( ) to force the order of evaluation (expressions within parentheses will always be evaluated first).

Here are some examples of expressions:

sum2 / n

(a * b - c) / (d - 2 * e)

( (b + 2 - 4 * a * c) ) / (2 * a)

50 % 12 // get the remainder of 50 divided by 12

Boolean/logical variables are evaluated in a similar way. The operator & lias a higher precedence than the operator I. Again, parentheses maybe used to force the order of evaluation.

3.6 Assignment Statements

All data must be stored in the computer’s memory before they can be used in computations. Each memory location lias a physical address, but we use a variable to reference it.

The assignment statement is used to store the result of an expression, ft takes the form:

variable = expression;

It can be interpreted as follows: evaluate the expression on the right-hand side of the operator (=) and assign the result to the variable on the left-hand side. The expression on the right-hand side can be a constant, a literal or an expression. Here are some examples of assignment statements.

age = 20; more = true;

greetings = "Hello there";

MyName = "Maria";

pay = basic + allowance + hours_worked * rate; net_pay = pay - 0.12 * pay;

The examples below show the contents of the variables ‘before’ and ‘after’ the assigmnent for the first four statements above.

Before After

Abbildung in dieser Leseprobe nicht enthalten

There are also short-hand assigmnent operators: *=, +=, -= and %=. If these operators are used, the variable on the left-hand side also acts as the first operand in the expression on the right-hand. For example, if X = 8 and y = 5, you will liave the following results.

Abbildung in dieser Leseprobe nicht enthalten

3.7 Type Casting & Boxing/Unboxing

You would normally ensure that the data type of the variable on the left-hand side of the assigmnent operator is the same as the data type of the expression on the right-hand side. If the data types are not the same, there might be errors in the computation e.g., loss of precision. To convert data from one type to another, you could use type casting. It takes the form:

(data type) variable

For example, if X is an integer variable and y is a double variable, then the statement

y = (double) x;

would convert X to double before assigning it to y.

Similarly, if X and n are integer variables, and y is a double variable, then the statement

y = (double) X / n;

would convert X to double before dividing it by n and assigning the restìi to y.

The data type of the variable on the left-hand-side of the assigmnent operator must be long enough to hold the value of the expression on the right-hand side.

The type casting also applies to a subclass object that is inherited from a super class. (For more information on subclass, superclass and inheritance, see Chapters 2 and 12.) To illustrate, if s is an object of type sub and s s is an object of type sup, and if s ub is a subclass of s up, then the statement

s = (sub) ss;

will cast the super class object s s to the subtype before assigning a reference to s.

c# treats all variables and values as objects, ft uses a special data type called object which will accept values of any data type whether they are value or reference type. Sometimes it may be convenient to treat a value type variable as an object. To illustrate, consider the code below.

int X = 5 ;

object y = x; // box a number

int z = (int) y; // unbox a number

Assigning a value-type variable to an instance of an object is called boxing. The reverse, i.e., converting an object type to value-type variable is called unboxing.

Normal or ordinary variables are allocated memory on the stack whereas instance variables are allocated memory on the heap. The memory allocation on the stack and heap for the above code is shown below.

You must be careful when you unbox an instance variable. For example, the code below will result in a compiler error because you are trying to put a long (bigger) value (stored as object in y) into an integer variable (z).

long X = 12345; object y = x;

int z = (int) y; // unboxing a long

Abbildung in dieser Leseprobe nicht enthalten

Why do you need stack and heap data structures? c# stores normal variables on the stack as it knows exactly how much memory they need. Instance variables, however, are different. They are created dynamically, on the fly, at runtime. The memory requirements change as instances are created and destroyed (deleted), c# provides a memory manager called garbage collector to reclaim memory on the heap when objects are deleted.

3.8 Checking and Unchecking

Variables of different data types require different amounts of memory. For example, an integer variable can store a value of up to 64 bits (8 bytes). The largest number it can store is 2,147,483,647 and the smallest number it can store is -2,147,483,648. If you exceed beyond tins range, you will get an overflow error.

Program 3.1 illustrates tilis.

Program 3.1 using System;

Abbildung in dieser Leseprobe nicht enthalten

The program will output an incorrect answer:

Abbildung in dieser Leseprobe nicht enthalten

To overcome tilis type of error, c# provides the checked and unchecked types which take the forms:

checked (expression) unchecked (expression)

When you use checked, the system throws an exception as Program 3.2 illustrates.

Program 3.2 using System;

Abbildung in dieser Leseprobe nicht enthalten

When you run tilis program you will get the below error message in a dialog box:

Y ou can catch the error by recoding the program as in Program 3.3.

Program 3.3 using System;

Abbildung in dieser Leseprobe nicht enthalten

You will get the same error message as before, but your program will catch the error. The unchecked simply reverses the effect of checked as inProgram 3.4.

Program 3.4 using System;

Abbildung in dieser Leseprobe nicht enthalten

The code produces wrong result:

Abbildung in dieser Leseprobe nicht enthalten

[...]

Excerpt out of 309 pages

Details

Title
Learn C#
Subtitle
The Easy Way. Through Examples
Course
Princeples of Programming
Grade
14
Author
Year
2018
Pages
309
Catalog Number
V435400
ISBN (eBook)
9783668794191
ISBN (Book)
9783668794207
Language
English
Tags
learn, easy, through, examples
Quote paper
Prof. Dr. Palaniappan Sellappan (Author), 2018, Learn C#, Munich, GRIN Verlag, https://www.grin.com/document/435400

Comments

  • No comments yet.
Read the ebook
Title: Learn C#


Upload papers

Your term paper / thesis:

- Publication as eBook and book
- High royalties for the sales
- Completely free - with ISBN
- It only takes five minutes
- Every paper finds readers

Publish now - it's free