+ All Categories

CSharp

Date post: 07-Nov-2014
Category:
Upload: kris2tmg
View: 37 times
Download: 2 times
Share this document with a friend
Description:
Santosh khuray
Popular Tags:
115
Table of Contents Installation of IDE:................................................4 First C# application................................................5 Creating a new project:...........................................5 First Program:....................................................6 Files in our program:.............................................8 Saving and Closing the projects:..................................9 Analyze the first C# application....................................9 Methods, Classes and Namespaces..................................11 Using Statements:................................................11 Visual Studio IDE overview.........................................12 Variables Declaration and assigning values.........................13 Duplicate Variable Names:........................................17 Code Commenting....................................................18 Accepting inputs in command line applications....................20 The” if” Decision Statement......................................22 Variable Scope:..................................................24 Introduction to .NET Framework.....................................26 IDE states.......................................................28 Operators, Expression and Statements...............................28 Member Access and Method Invocation Operators:...................30 Data Types.........................................................30 Boolean Types:...................................................31 Integer Types....................................................31 String Type......................................................31 Char Type........................................................32 Floating Point...................................................32 Decimal Types....................................................32
Transcript
Page 1: CSharp

Table of ContentsInstallation of IDE:...................................................................................................................................4

First C# application..................................................................................................................................5

Creating a new project:.......................................................................................................................5

First Program:......................................................................................................................................6

Files in our program:............................................................................................................................8

Saving and Closing the projects:..........................................................................................................9

Analyze the first C# application...............................................................................................................9

Methods, Classes and Namespaces...................................................................................................11

Using Statements:..............................................................................................................................11

Visual Studio IDE overview....................................................................................................................12

Variables Declaration and assigning values...........................................................................................13

Duplicate Variable Names:................................................................................................................17

Code Commenting.................................................................................................................................18

Accepting inputs in command line applications.................................................................................20

The” if” Decision Statement..............................................................................................................22

Variable Scope:..................................................................................................................................24

Introduction to .NET Framework...........................................................................................................26

IDE states...........................................................................................................................................28

Operators, Expression and Statements.................................................................................................28

Member Access and Method Invocation Operators:.........................................................................30

Data Types.............................................................................................................................................30

Boolean Types:..................................................................................................................................31

Integer Types.....................................................................................................................................31

String Type.........................................................................................................................................31

Char Type...........................................................................................................................................32

Floating Point.....................................................................................................................................32

Decimal Types....................................................................................................................................32

Common Type System (CTS)..............................................................................................................33

Special Data Types.............................................................................................................................33

Page 2: CSharp

Control/Decision Statements – if, Switch and Conditional Statements.................................................34

The if Statement................................................................................................................................34

The switch Statement........................................................................................................................35

Differences between Switch and If-else.............................................................................................38

Iterations...............................................................................................................................................38

For Loop.............................................................................................................................................39

While Loop.........................................................................................................................................40

The do Loop.......................................................................................................................................40

The foreach Loop...............................................................................................................................41

Arrays....................................................................................................................................................42

Debugging using IDE..............................................................................................................................43

Watch Window..................................................................................................................................44

The autos window.............................................................................................................................44

The locals window.............................................................................................................................44

VISUAL STUDIO IDE: Code Snippets, managing Tabs, intermediate Window....................................45

Code Snippets:...................................................................................................................................45

Managing Tabs..................................................................................................................................47

Immediate Window...........................................................................................................................48

Navigating through code...................................................................................................................48

Object Oriented Programming..............................................................................................................49

Encapsulation....................................................................................................................................49

Methods, Fields and Properties.........................................................................................................51

Instantiation of a class with a new operator......................................................................................53

Inheritance............................................................................................................................................55

Overriding Methods and Properties..................................................................................................56

Constructors......................................................................................................................................59

Overloading Methods and Contructors.............................................................................................59

Abstract.................................................................................................................................................59

Use with Classes................................................................................................................................60

Use with Methods.............................................................................................................................60

Use with Properties...........................................................................................................................60

Interface................................................................................................................................................61

Page 3: CSharp

Differences between Interfaces and abstract classes........................................................................62

sealed....................................................................................................................................................63

static......................................................................................................................................................63

Access Modifiers....................................................................................................................................64

Arrays and Collection of Objects............................................................................................................64

Arrays of Objects...............................................................................................................................65

ArrayList.............................................................................................................................................67

Generic Collections............................................................................................................................69

Polymorphism via Inheritance...............................................................................................................72

Polymorphism via Abstract Class...........................................................................................................75

Polymorphism via Interfaces.................................................................................................................76

Association of the Objects.....................................................................................................................77

Aggregation.......................................................................................................................................77

Containment/Composition................................................................................................................79

Enumerations........................................................................................................................................81

Value Types...........................................................................................................................................82

Main Features of Value Types...........................................................................................................82

struct.....................................................................................................................................................83

Constants...............................................................................................................................................84

Casting...................................................................................................................................................84

Boxing and Unboxing.............................................................................................................................84

Object and Collection Initializers...........................................................................................................85

Exception handling................................................................................................................................86

Introduction to UML and Class Diagrams..............................................................................................90

Relationships in UML.........................................................................................................................91

Aggregation Relationship...................................................................................................................91

Containment or Composition Relationship........................................................................................93

Static and Inheritance........................................................................................................................95

Abstract Class/Methods....................................................................................................................96

Interface............................................................................................................................................97

Page 4: CSharp

Installation of IDE:1. IDE stands for Integrated Development Environment. This is the tool we will be using through

out the course to write or develop C# programs and other .NET projects.2. MS provides 5 types of VS editions out of which 1 is free Visual C# Express Edition (is part of the

Visual Studio 2010 Express family).3. Follow the below steps to install the tool on your machine.

a. Go to www.Microsoft.com/express/express-2010b. Select the Visual C# Express linkc. Select the appropriate language and click “Install now” buttond. Once the download is complete, navigate to the path where the files have been

downloaded to. e. Double-click on the vcs_web.exe file.f. After clicking Next till you see the actual installation screens, please make sure to check

the optional Microsoft SQL Server express edition service pack 1.

g. You will be prompted to restart your machine. This is because of the .NET framework 4.0 installation which is foundational.

Page 5: CSharp

h. Once the machine starts, the installation will continue.i. Once the installation is complete, go to the start menu on windows.j. Click the “Microsoft Visual C# 2010 Express” icon to load up for the first time which may

take few moments to load completely.

First C# applicationIn this session we’ll learn the following

1. Creating a new project2. How to and where to write the code and build errors3. How to save and close the projects4. Where to look for the project files in windows explorer5. How to open the existing project.

Creating a new project:1. Load up the IDE by clicking on the icon in the start menu.2. You should see the start page with couple of options and links on the top left corner of the page.

a. New Project b. Open Project

Page 6: CSharp

3. Because this is our first project and we do not have any projects already with us, we will go by clicking on the “New Project”

4. On the following page, select C# console application. You may be very rarely using such projects in your real life projects but this would be a good place from where you can start learning the C# fundamentals.

5. Change the Name to Session 1 and then click OK.

First Program:1. Copy this line of code into the curly braces under “static void main. (This statement will print the

text on the windows console. You’ll understand later in this session.)Console.WriteLine("Hello World");

NOTE: Make sure you write the code within the curly braces failing which results in unwanted errors while building (called build errors).If you write the code outside the braces you can see the errors.All the code wit in the braces is called a code block. The reason for writing it with in the braces is because the main method is the one that gets executed first by default when the program runs. We’ll talk more about methods later. But, all we need to remember from this is where to write the code to begin with.

NOTE 2: Always use semicolon to end the statement.

Page 7: CSharp

2. Click on the green triangle button (which is to Start debugging).It should open up a black screen (command prompt window) and closes immediately. This means that the program has ran successfully but you did not get a chance to see what was on the screen.

3. Now, let’s add one more (below) line of code under first line that we have added in step 6. (This statement will pause for the application for a moment, waiting for input before it would continue on. You’ll understand it when you run the application.)

Console.ReadLine();

If you run the program by clicking on the green triangle button (start debugging) or by going to Debug Menu and click on “start debugging” you should see the command prompt window displaying “Hello world” message.

Page 8: CSharp

This window is called Windows Console Window. If you hit any key on the key board the window will exit.

Files in our program:

1. IDE will help you in organizing the projects, managing the files, compiling the programs. We’ll talk more about different types of projects in the future sessions.

The right side window called “Solution Explorer” lists out the files. There are several options on the toolbar menu.

Page 9: CSharp

Saving and Closing the projects:1. As we have learnt how to and where to write the code, how to run it and what kind of

windows are there in IDE, let’s now see how we can save the project and close out of it.a. Go to File menu on the top corner left.b. Click on Close Solution. If it asks you “do you want to discard the changes” say No

and pick the default location (do not browse to a new location so as to understand this session easily). Please remember the path.

c. Now go to your documents folder and open up Visual Studio folder double click on Projects folder. Then, you can see Session1 solution folder. In that there is a file called Solution File.

d. You can see that there’s another Session1 file when you go into the Session1 folder but this time it’s a Visual C# project file. We’ll talk more about solutions and projects in the next sessions. Here’s the program.cs file that we saw earlier, and then if we look in the bin directory we would see two folders called Debug and Release.

e. Look into the Debug folder, you should see an executable file called as Session1.exe. This is where the EXE file was created whenever we hit ‘start debugging’ on our application in the IDE. We’ll talk more about the difference between Debug and Release folder in the later sessions.

Opening the existing projects

1. In the beginning of this chapter we have learnt how to create a new project from the couple of options given to us on the start page. Now, we’ll learn how to open the existing project.

2. 3 options for us to open the existing project.a. Click on the Open project link on the start page and browse t the solution file of the

Session1 application.b. Go to File menu and select “Open Project” which should pop up a window for you to

browse to the solution filec. When you look at the start page, you can see the “Session1” project under Recent

Projects. You can click on that to open up the project directly. If you are working on multiple projects and want some projects to show up on the top of the list under “Recent Projects” section then use the pin beside the project name. (just like the one in front of Session1”.

Analyze the first C# applicationIn the previous chapter we have learnt how and where to write the code. Let’s start from those two lines of code you have written in the previous chapter.

Understanding the Keywords Console, .NET framework Runtime, Classes and Methods.

Page 10: CSharp

1. The .NET framework is a platform in which our applications reside. Below are some significant the framework does.

a. The code runs inside the .NET framework Runtime which is an application that wraps around our application. The Runtime is very very important and takes care of the following low-level tasks

i. Manages the data flow of an application into and out of the memory.ii. Provides protection from accidentally crashing the computer

iii. Provides a library of functionalitySo when we write the code using these libraries then all the underground work like printing, reading and writing to files etc will be managed by it (libraries).This library of functionality is called .NET Framework Class Library (FCL) or Base Class Library (BCL).

b. When the line Console.WriteLine("Hello World"); is written we are actually telling the FCL to do something which in this case is to write a line “Hello World” to Windows Console. The library is going to take care of doing all that low-level tasks for us. The Console part of that line is called as a class and the WriteLine is a method. The entire task will be handled by that method.The same console class has another method called “ReadLine”. All the code that deals with Windows Console gathered together and organized to form something called a class named Console.

c. The “Hello World” is written in the braces of WriteLine method. This is called passing in the parameter. “Hello World” is the parameter that we are passing into that method. A

Page 11: CSharp

method may or may not accept parameters. For instance, ReadLine() method doesnot accept any parameters. “Hello World” is a literal string that we want to see on the console window, so it needs to be double quotes. Literal string means literally that’s what you want to see. In next sessions, You will learn more about the parameters.

2. Now, look at the Main method in which we called the two methods of Console class. It is accepting a string[] args and this is already been passed by the Framework as this is the first method that gets executed in the case of this console application.NOTE: So far we’ve learnt that A method is a named block of code and a Class is a container of methods.

Methods, Classes and Namespaces

1. When you look the Program.cs file. There is a class called Program in which main is a method.2. Outside the class Program there is namespace Session1.3. You can have multiple classes under same namespace. 4. Think of namespace as LastName and classes as FirstNames. Multiple people can have same first

name which means classes can be of same name and we’ll talk more about it later. 5. So, if you want to call a class use the namespace along with the class so as to avoid the

ambiguity. For example, if you want to call Santosh in a particular class there may more than 1 santosh. But if you call Kor.Santosh there will be only one.

6. Whenever we use classes from FCL or custom libraries it should be used with namespaces (last names) in order to avoid ambiguity (nothing but confusion)

Using Statements:1. When we look at the Console class we have not mentioned any namespace infront of it. It actually

belongs to “System” namespace. See the first top most statement in the Program.cs file there should be a using System; This is the way of telling the program that whenever you see Console, just assume that we’re talking about System.Console. This is just to minimize the typing. Whenever we create a new project/file the IDE automatically writes some common namespaces as using statements.

To review what was discussed in this section:1. A method is a named block of code in C#. 2. A block of code is defined with curly braces.3. A method can accept parameters as a means of sending information into the method for processing.

The words ‘hello world’, a literal string of characters, were sent into the WriteLine method for processing. In this case it used that literal string that we passed it to be displayed on-screen.

4. Parameters are accessed using an open and closed parenthesis.5. Microsoft created the .NET Framework Class Library, which contains thousands of methods that we

can call by name to perform various low-level tasks. This allows a developer to focus on the important functionality within applications.

Page 12: CSharp

6. Classes are a means of organizing common methods together. Remember – this is just a working definition for now.

7. Namespaces are a means of removing ambiguity and confusion, much like the reason for your last name, or your surname. It’s like a last name for classes. This is what Microsoft has done for all of its classes. It helps to organize their massive library of code into logical containers that help developers find what they’re looking for, in order to more easily memorize and find those methods that are actually needed from the Framework Class Library.

8. Using statements: Typically this is placed at the very top of the code file, so that a developer doesn’t have to type the entire namespace used by the classes and the methods in the main code body.

9. The semicolon is like the period at the end of the complete thought within the code. 10. Indentation and code coloring are a way to help you and others read code.

Visual Studio IDE overviewIn this session we’ll learn the following

1. how to use IntelliSense to ensure correct spelling, and to speed your coding.2. how to use Tool Tips to learn additional information about your code3. how to use line and column numbering to locate code.4. how to customize the IDE by displaying line numbers, and how to change both font and colors.5. how to track changes in your code.

Intellisense helps the programmer to be more efficient. Delete the lines and start retyping in. As soon as you start typing the popup is going to give you number of options which you can use to program. When you do a period after Console. it is going to give you the options that are available form Console class. You should also see the tow methods that we have called in our first C# application.

Intellisense is based on the context. If you strat typing in the WriteLine to begin with (after deleting the two lines) you will be seeing the different options opposed to when you have seen after typing in a period(dot) beside Console class.

There are several important elements at the bottom of the Visual Studio IDE window.

Ready – This tells us that we can work with the IDE now; that it’s not busy doing something. Ln tells us what line number we’re on. If you use the arrow key on your keyboard to move up or

down, you’ll see the line number change. Col tells us what column number we’re on. If you use the arrow keys on your keyboard to move

left or right, you’ll see the column number change. INS is the insert mode. This can be changed with your keyboard options, depending on what

keyboard options you’ve selected.

Line numbers also help identify and correct errors in your code. If you have an error, the Error List will display both the line number as well as the column number.

Page 13: CSharp

Go to the tools menu and select options

In the new window, select the text editor portion and go to the C# option and expand it You’ll see that there are many options with regards to how the IDE displays and behaves.

To the right of the line numbers you can see little minus signs in a box. These are sections of code, called code blocks. When you’re not dealing with a particular section, you can roll it up to avoid distraction.

Yellow lines means we need to save and green lines are already saved.

Variables Declaration and assigning valuesIn this section we’ll learn the following

1. you will learn what a variable is, 2. how to declare a variable 3. how to initiate (or assign a value to) a variable4. A variable can be declared and initiated in two separate steps, or combined into a single step. 5. C# is a case-sensitive language, and that you should use camel casing to improve your code

readability.

Consider the following algebra equations.a = 5;b = a + 10;Console.WriteLine(b);

is going to throw 15 as result. When you want to program this you can’t just write the above 3 statemets in the C# as it would throw errors because it will be unable to recognize what a and b are. a and b are called as variables which are nothing but buckets that hold the values in your computer’s memory. We know that both of them are holding integer values but C# and .NET framework runtime does not. So we have to use C# to express the same to .NET runtime. This we can do it by declaring the variables. See below.

Page 14: CSharp

We have declared out variables as integer (that has no fractions or decimals). Likewise, we can declare the variables as decimals, strings and so on. We’ll talk more about different type of variables in the next sessions. Now, as we have declared them as integers, runtime will allocate the memory for those variables.Let’s assign some values to these variables. We will use = sign for assigning in C#. Type in the assigning statements (see below).

If you run this program you should see a windows console window with 15 as the result.

Let’s try some string variables. Here a string variable called “myCity” is declared.

Page 15: CSharp

While trying to assign a value to the “myCity” string the intellisense popped up and showing us the variable name. As we have mentioned earlier in our previous chapters this is how the intellisense can be used (which comes along with the tooltips that describes the options in the popup).

Page 16: CSharp

Now when you run the application, it would show you 10 as result and waits for you to key in some letter and then it shows you “dallas” and exits as soon as you key in something again.

Instead of declaring and assigning the variables in two different statements you can do both of them in single statement. For instance, let’s consider the string variable “myCity” we were just playing with. You can do both those lines in the way shown below.string myCity = "dallas";

This would save time and is a best practice to do.

Page 17: CSharp

Look at the way variable is names. First letter is small and the first letter of the next word is a capital. This is called as camel casing and this is preferred while coding to improve the code readability.NOTE: Some programmers use _ (underscore) infront of the names. This is basically vb coding. You can use this also but camel is preferred by most of the C# programmers.

Duplicate Variable Names:Now type in int A;statement. Here we are declaring a variable called A as an integer. C# is a case sensitive language and so a and A will not be trated as same.

When you type in a new statement int a; and try running the application it would throw you the build error saying A local variable named 'a' is already defined in this scope.This means that you cannot decalre the variables with same name in the same scope. We’ll talk more about scopes later but in this example in the same main method we cannot have two variables with the same name.

Page 18: CSharp

Code CommentingThis code will not compiled/processed/executed by the .NET framework runtime.

We write the comments to add the following

1. Explanation to the code (for your understanding or for others who might be trying to understand your code).

2. To temporarily remove some code form the compilation process.3. To remind you off any unfinished work that you might want to come back in the future (TODOs).

There are more than one way of commenting.

Put two forward slashes (//) before a line to comment that line of code.

//Console.ReadLine();

To comment out the multiple lines of code or to write some notes you can also use /* */

Page 19: CSharp

Please make sure to end the comments with */ otherwise all the code after /* will be commented out. (Please try it out yourself and see).

Third way of commenting is by using the “Comment out the selected lines” button from the toolbar. You can use this button to comment out the multiple lines as well.

Page 20: CSharp

NOTE: You can also include urls in the comments.

Accepting inputs in command line applicationsLet’s see how we can accept the input from the console application. We’ll see how to allow users to type something in and how we can make use of that value in the code from the console window.

Type in the following code in your first C# application.

Page 21: CSharp

Please go through the comments in the code for better understanding.

When you run the application, you should see the following result after typing in your name and pressing enter key.

Page 22: CSharp

The” if” Decision Statementif is one of the conditional statements in C# which can be used to decide something in the program. Look at the following sample code. Let’s go one by one statement and what each of them is doing.

In line 14 we are calling WriteLine() method to ask the user a question.

In line 18, we have declared a variable and assigning the value user has entered in the console window to it. You can also write this statement as follows (into two separate statements).

string input; input = Console.ReadLine();

Page 23: CSharp

In line 21, you can see a if statement which is checking to see if the user input is “y”. In C#, we use == operator to see if they are equal and = sign to assign the value. We’ll talk more about operators in the future sessions. If the condition in line 21 satisfies then it executes the code with in the curly braces after that condition. So, the result would be as shown.

In line 26, there is an else if statement which gets executed only if the condition in line 21 does not satisfy. Line 26 will check to see if the user input is “n”. If so, it will execute the following code block in the braces. The result will be as shown below.

Page 24: CSharp

Line 31, has else statement which gets executed only when the above two conditions does not satisfy. The result would be like shown below.

Variable Scope:The code blocks (nothing but the code within the curly braces { }) define the scope of the variables. Consider the following example in the screenshot.

Note that Main method itself is code block and the code within the curly braces after if statement is a code block.

In lines 13 and 16, two variables a and b are declared in the main method. In line 21, variable b from main method is being used in if code block. When you run the sample you should see the result 10 on the console window without any issues. It means that we can use variable b in both main and if code blocks.

Page 25: CSharp

Now, let’s look at the following sample (see screenshot below).

In line 21, we have declared a variable c of type integer and assigned a value of 20. Note that we have declared it within the if code block. Now, look at line 25, we are trying to access the same variable c in the main code block and when you run it, it is going to throw the build error saying “The name 'c' does not exist in the current context”. This means that the variable declared in the if block cannot be used in the main method which 1 level above the if block. So, the scope of the variable c is just the if block.

NOTE: the variables declared in one method cannot be used in another method which is a separate code block. There are ways of declaring variables to be accessed by multiple methods but we’ll learn it in the future sessions. For now, just think about the variable scopes and try playing with them.

Page 26: CSharp

Introduction to .NET FrameworkWe’ll learn

1. How it executes our code and 2. How it interacts with the code that we write

In the earlier sessions we discussed that .NET Framework runtime is a protective layer on top of our application and it manages the allocation and de-allocation of the memory to the variables. It also protects the end users machine from un-authorized access to the important resources like hard drive.

NOTE: It is a protective layer that benefits both end user and the developer.

Page 27: CSharp

When you write a C# code, in order for that application to be executed and do something, it has to be compiled.

Compilation is a process that converts human readable C# code into machine-usable/readable code. The end result of a compilation is a file called an assembly. There are two types of assemblies.

1. .exe files (executable assemblies)2. .dll files (dynamic link library) It is a supporting library of code to be used by other executing

code. We’ll talk more about them when we try to architect our application for re-use (interesting).

The entire compilation process happens in 2 phases.

1. The 1st phase happens when you begin debugging. When you begin debugging, a debug version of the assembly will get added in the debug folder. We have seen this in the First C# application path.

2. Release version of the assembly will get created in the Release folder.

Debug Assembly Release AssemblyGets created when we start debugging the code. Will be in Debug folder under bin directory.

Will be in Release folder under bin directory

Has some additional information added to the assembly to enable the IDE to participate in the execution of the application in debug mode.

If you want to give your application to somebody else then at a minimum we have to give them the Release version and they also gonna have to have the .NET Frmaework runtime.

During the Compilation process the compiler takes the C# code and turns it into the assembly file.

C# Compiler Assembly

The compilation process does a few things during the process of converting the C# code to an assembly.

1. Parsing and Compiling into Common Intermediate Languagea. It starts by parsing and validating your C# code.b. Once it passes the first check then it converts the C# code to common Intermediate

language (CIL or intermediate language IL).c. Compiler adds the bootstrap code calling the .NET runtime. It adds any additional

programs that need to go along with this assembly or executable file.2. Just-In-Time Compilation (JIT).

a. The end users machines can have different types of operating systems, configurarions and hardware. While developing the program the developer do not have to worry about these low-level details. JIT takes the CIL of our assembly and then it compiles the best version based on end user’s version of windows, software, configuration and hardware.

Page 28: CSharp

It saves the application (optimized version) in a cache for future use on the end users’ hard drive. So, whenever the application is ran again on the end users’ machine the .NET Runtime will use the optimized version that cached on their machine.

NOTE: This is all done in the background without the knowledge of a developer.

IDE states1. Design Time: It’s a state of IDE which refers to those activities that take place while developer is

writing code. Actor is Developer and he is the one working mainly on the application while designing it.

2. Compile Time: When you decide to debug or compile your applciaiton, that process of creating debug or release version of the assembly is called Compile Time. This time depends on the lines of code that you are trying to compile. Actor is Compiler as it is the one which compiles the whole c# code to assemblies.

3. Run Time: This is when our application is actually executing. During this time the .NET framework will be working with the compiled version of your code to perform the instructions that we programmed.

During this time and expected bugs or errors/exceptions happen which can cause the app to break. We’ll learn about how to write code to handle these in the future sessions.

4. Debug Time: This is a mix between design time and run time. This is referred to as debugging. Debugging is a process where IDE can let you step through each line of code and examine the values that are currently stored in the variables. This is a very important feature of IDE.

Operators, Expression and StatementsStatements: It is a complete instruction. It contains one or more expressions.Expressions: They are made up of operators and operands.

If you look at the previous code line we wrote, we used a condition statement

if(input == "y")

input == "y" is an expression and the whole sentence is a statement.

In the same way in the below line of code.b = a + 10;

a + 10 is an expressiona is an operand and + is operator.

Operands: They are nothing but variables (like a, b in our previous examples), Literal strings (like "Hello World!"), and Objects (like Console class. We’ll talk about them in the future sessions).Operators: Below are some operators used in C# language.

Below is the screenshot listing various operators used in C#.

Page 29: CSharp

You will be majorly using the following few operators in the below statements.b = a + 10; Assignment and Addition Operatorsx = y - 10; Assignment and Subtraction Operatorsa = 2 * 10; Assignment and Multiplication Operatorsx = 20 / 2; Assignment and Division Operatorsif(input == "y") Equality Operator This operator returns true or false.if(a > b) Greater than Operatorif(a < b) Less than Operatorif(a >= b) Greater than or Equal to Operatorif(a <= b) Less than or Equal to Operatorif((a < b) && a == 10)) && is an AND Operator. The condition is true only if it satisfies both the conditionsif((a < b) || a == 10)) || is an OR Operator. The condition is true only if it one of the conditions satisfies.

Conditional Operator: It is short hand for the if statement. Look at the below code.

We are setting the value of variable c to a or b depending on the condition (a > b). If the condition satisfies then the value of c will be equal to a or else it will be equal to b.

Page 30: CSharp

Member Access and Method Invocation Operators:In the below line of code

Console.ReadLine();

The dot notation is going to give us the access to the members of Console class. Parenthesis () are used for Method invocation.

For better understanding let’s categorize the statements.

1. Code blocks are one type of statements. We have used them in namespaces, classes, methods, if conditions.

Code Block { //code here }

2. Declaration Statements:

int a;We can combine these with the initialization statements.

3. Expression Statements:

int c = a + b;NOTE: same rules as algebra get applied in C#. Example (a*10) + 20; Here first a+10 gets executed and then added to 20 to give you the final result.

4. Selection (Decision) Statements: if (a > b)

{ c = a; }

5. Iteration Statements: We’ll talk more about them in the next sessions.

Data TypesSo far, we have used int and string data types.

Below are different types of data that comes with C# language.

1. Boolean type2. Integrals Numerical3. Floating Point Numerical4. Decimal Numerical5. String

Page 31: CSharp

Boolean Types:They are declared using the keyword bool.

bool isCorrect = false;

The value will be either true or false. The space occupied by a Boolean variable is 1 byte (8 bits).

Integer Types These are numeric values either signed or unsigned holding values with no decimal points.

Below is the table that lists all the integral data types.

String Type These are textual data surrounded by double quotes or a sequence of text characters.

C# has a special syntax where characters can be escaped to represent non-printable characters. For example, it is common to use newlines in text, which is represented by the '\n' char. The backslash, '\', represents the escape. When preceded by the escape character, the 'n' is no longer interpreted as an alphabetical character, but now represents a newline.

The same way, if you consider Console.WriteLine method and if you want to show double quotes on the console window then you have to use ‘\’ backslash to represent the escape and ‘"’ double quote as escape character.

The below line of code would produce the result as in the screenshot.

Console.WriteLine("\"Trying to show double quotes.\"");

Page 32: CSharp

Below are some character escape sequences

Char TypeThis represents a single Unicode character numerically.

Floating Point In C# the floating point types are float and double. They are used for real numbers. See below for the size and precisions. Floating point types are used when you need to perform operations requiring fractional representations.

Decimal TypesDecimal types will be used for storing money (in the financial cases where you do not wish to round the figures).

Page 33: CSharp

Common Type System (CTS)One of the main services .NET provides is this CTS. All the data types like int, string (not just in C# but in any language supported by .NET ) will be extended out from the common data types in this CTS.

int from System.Int32

string from System.String

Each data type has some limits on what it can store and those limits are based on the size of the variable.

Special Data Types

DateTime Data typeThere is a special data type System.DateTime which belong to the .NET Framework class Library (FCL) and there is no equivalent data type for it in C#. See below line of code to learn how to declare and initialize the datetime variable.

DateTime is a complicated type as it includes more complicated data including year, month, day, hours, minutes and seconds.

We can treat almost everything in the .NET as a datatype. All the classes can be treated as data types (you’ll learn more when learning about OOPS).

Page 34: CSharp

Object data typeThe object type is referenced from System.Object data type in .NET Framework. Values of any type can be assigned to the variables of type object. This is the one from which all the other reference types derive.

int i = 10; object obj; obj = i; //integer value obj = "something"; //string value

It’s very important to remember that since the C# int data type is referenced from System.Int32, the methods from Int32 like Parse(), ToString() can be used with int in C#.

int i = 10;

//ToString() method is from System.Int32. //ToString() method converts the integer value to a string. string str = i.ToString();

Same way, Parse() method is implemented in Int32 and can be used with int in C#

string str = "10"; int i = int.Parse(str); //Parse() method is from Int32 // The value of i is now the integer 97.

Control/Decision Statements – if, Switch and Conditional StatementsIn this section you’ll learn the following

1. if statements.2. switch statement.3. how break is used in switch statements.4. proper use of the goto statement.

The if StatementDepending on a given condition, an if statement allows you to take different paths of logic. If the condition specified in the if statement is satisfied then the block of code following the if statement will get executed. You can write single if statement or multiple if statements using else if statements (just like the one we wrote in one of you last sessions). Please refer to Chapter 6 notes to learn more about the if statements.

Page 35: CSharp

The switch StatementThe switch statement is another form of selection statement. This executes a set of logic depending on the value of a given parameter. Below are the types of the values a switch statement operates on

a. Booleansb. Enums (you’ll learn more about them in the next sessions).c. integral typesd. strings

The same if else statements from the above screen shot can be written using switch statement. See below.

Page 36: CSharp

This would give the same result as in the case of if statements.

The switch block follows the switch expression, where one or more choices are evaluated for a possible match with the switch expression. Each choice is labeled with the case keyword, followed by a value that is of the same data type as the switch expression and followed by a colon (:). In the example we have case "y": case "n": When the result evaluated in the switch expression matches one of these choices, the statements immediately following the matching choice are executed, up to and including a branching statement, which could be either a break, continue, goto, return, or throw statement. Below are the branching statements we use with switch statements.

break: Leaves the switch block

continue: Leaves the switch block, skips remaining logic in enclosing loop, and goes back to loop condition to determine if loop should be executed again from the beginning. Works only if switch statement is in a loop. We’ll talk more about them in the next sessions.

goto: Leaves the switch block and jumps directly to a label of the form "<labelname>:"

return: Leaves the current method. We’ll talk more about Methods in the next sessions.

Page 37: CSharp

throw: Throws an exception. We’ll talk more about them in the next sessions.

Below is the screenshot displaying code that uses the goto statement along with the switch statement.

When the user input is “y” it executes the line 24 and then looks at line 25 where we are asking it to discontinue the flow of the program and jump to CASE_YES. So, it directly executes line 37 and all the lines below it. Note that it also executes the lines under CASE_NO and DEFAULT_CASE as we have used a got statement which executes all the statements from that label onwards (in this case from CASE_YES).

In case, if you type y in the console window the result will be as shown below.

Page 38: CSharp

Differences between Switch and If-elseBelow are some of the differences between switch and if statements.

switch

a. More readable because of it’s compactnessb. If you omit the break between two switch cases, you can fall through to the next case. c. Switch only accepts primitive types as key and constants as cases. This means it can be

optimized by the compiler using a jump table which is very fast.

if-else

a. if allows complex expressions in the condition while switch wants a constantb. With if else you'd need a goto

For inline options, we can use conditional statements as we have discussed in the earlier sections.

IterationsLoops allow you to execute a block of statements repeatedly. C# has several statements to construct loops with, including the while, do, for, and foreach loops.

Page 39: CSharp

For Loop

If you look at the sequence of statements inside the parenthesis () after for. There are three statements in the parenthesis and let’s discuss about each of them.

1. You can see,

int i = 0; This is clearly a statement where we are declaring a variable I of type int and initializing to a value 0.

2. Next statement is i < 10; It is a condition that checks to see if interger variable I is less than 10. If so, it return true else false.

3. Next statement is i++ This is called as an increment operator. It is nothing but writing i = i+1;

By writing for loop, we are asking it to loop through the code block after for statements until the condtion i < 10; is true. Each time you finish iterate through the block of code it will increment the value of i by 1.

The result of the code in the screenshot above is as shown below.

Page 40: CSharp

Now, you can also implement various functionality in the for loop. For instance, checking for some value of I and if it satisfies do something.

While LoopA while loop will check a condition and then continues to execute a block of code as long as the condition i < 10 evaluates to a boolean value of true. The same for loop from above can be written suing the while statement as below.

When the i < 10 expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code. Before entering the loop, ensure that variables evaluated in the loop condition are set to an initial state (in this case i = 0). During execution, make sure you update variables associated with the boolean expression so that the loop will end when you want it to.

The do LoopA do loop is similar to the while loop. The only difference is that it checks its condition at the end of the loop which means that the do loop is guaranteed to execute at least one time. On the other hand, a while loop evaluates its boolean expression at the beginning and there is generally no guarantee that the statements inside the loop will be executed, unless you program the code to explicitly do so.

Page 41: CSharp

In the above code, the code block after do statement will get executed and then checks to see if the expression is true. If the expression is true then it executes the code block again otherwise gets out of the loop and executes the line 21. The result is shown as below.

The foreach LoopA foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace.

string[] names = {"Cheryl", "Joe", "Matt", "Robert"};

foreach (string person in names) { Console.WriteLine("{0} ", person); }

We’ll talk more about the foreach loop when we discuss about Arrays in the next sessions.

Exercise: Do the exercise to read a file and show what’s written in it on the console window.

StreamReader myReader = new StreamReader("sample.txt"); string line = "";

while (line != null) {

Page 42: CSharp

line = myReader.ReadLine(); if (line != null) Console.WriteLine(line); } myReader.Close(); Console.ReadLine();

ArraysArrays are collections of data. You can use it like any other variable but inside it contains more than 1 value (a collection of data). You can access the data from array variable using an index.

string[] names = new string[3]; We’ll talk more about the new operator in the next sessions.

Above line is the way of declaring and initializing an array. The square brackets [] are called the index access operator and this is what we’ll use to access a specific element of array.

The array elements are 0 based.Please read the comments beside each line for better understanding of how to access/read the elements of an array.

Arrays are of fixed size and .NET has to know how much memory need to be allocated to an array. So, we mention the length of the array on the right hand side square braces. IN the above case, it is 3.

If you try to access or set the 4th element of names array it would throw “Index out of range” exception as we have already mentioned while initializing array that the maximum number is 3 (index would be 2 as it starts from 0).

Exercise: Use different types of loops we have discussed in the earlier chapter to show all the names from the above array on the console window.

There is one more way of declaring and initializing the same array just in 1 line.

Page 43: CSharp

string[] names = { "Abi", "Bob", "Chaz" }; This statements does not need new keyword. It tells the C# that the maximum (or Length) of this array is 3. It also specifies value of each element in the array.

Arrays can be not just of strings but also of int or any other data types.

In our previous chapter while talking about foreach loop, we haven’t talked much about it as we were saying that it will be used with arrays, collections. Now that we have discussed on Arrays let’s see how foreach loop can be used. See below for the code block.

Please see the comments to get a better understanding of the foreach loop. Below is how the result would be.

Exercise to use Char and Char[]

Reverse the string and show it on the console window using char[]

string name = "Abi"; char[] charArray = name.ToCharArray(); Array.Reverse(charArray); Console.WriteLine(charArray);

Debugging using IDEDebugging feature will help us to step through the code execution step by step and see the values that are being held by the variables in a current context. It helps us to debug and find problems with our application. Help us to understand the code execution and flow.

First step to do debugging is setting a break point. You can do it in the following ways. First, use the toolbar menu option by going to Debug Toggle breakpoint. Second way is to use the shortcut F9. Third way is to right click on the line of code and select break point.

You can delete the breakpoint by pressing F9 or use the same toolbar menu option.

Page 44: CSharp

As soon as you run the application, the execution will stop and highlight the line of code where breakpoint has been set. You can use the mouse to hover at different variables to see what values are getting held by the variables in the current context.

Watch Window You can add watch to any variable to see what values are being held in them while the execution.

Note: Visual Studio 2010 has got a new feature of pinning the variable values to see what values are being held in the variables and leave some comments beneath the pinned window.

The autos window shows the current statement and the previous statement. it was always the previous statement that threw me off, as i never took the time to look closely enough to realize that’s where that variable was coming from.

The locals window shows everything currently in scope. Thus, the autos window is a subset of the locals window.

For example, consider the following code snippet that does nothing but produce warnings for unused variables:

In the Auto windows, you’ll see the previous statement and the current statement being evaluated:

In the Locals window, you’ll see the everything in scope, including the args parameter:

Page 45: CSharp

VISUAL STUDIO IDE: Code Snippets, managing Tabs, intermediate Window

Code Snippets: It is not easy to remember syntax for all of the code blocks like iterations, condition blocks, properties etc. These also help in reducing our typing.

For code snippet to write the template of the block on your file automatically write the keyword (let’s say if for if block) and then press tab key twice.

Same thing for the code blocks like for, foreach, while, switch etc..

If you want to see the option in the toolbox menu, then go to Edit and you can see “Insert CodeSnippets” or you have to go to “Intellisense” to see it or the shortcut keys are Ctrl+k+x

Page 46: CSharp

You can see the below list of code snippets you can use in your code.

Page 47: CSharp

You can also create your own snippets using “Snippet Editor” and take advantage of the snippets functionality in the IDE.

Managing TabsYou can re-order the tabs. There is a down arrow at the end of the tabs which you can use to pick the file you want to select and see.

You can right click on the tab and use various options including “New Horizontal Tab group” and “New vertical Tab group” which would let you work on multiple files at a time.

You can use “Move to Previous Tab group” option (from the options when you right click on the tab) to move the file back to its original tab group.

Page 48: CSharp

You can also use the drag option to place the file where ever you like. In VS 2010 you can also pull the tab out of the tool. You can use the splitter at the top right hand side corner under tabs to see the same class in two different panes.

Immediate WindowYou can use it while debugging. You can use it to display values using the ? operator. Immediate window allows you to modify variables in memory while the application is paused in debug mode.

NOTE:You can make the cursor go through the already executed line of code one more time by right clicking on it and selecting “Set Next Statement”

Navigating through codeName your files consistently. Use folders to organize them.

Below is how a class should be coded.

Page 49: CSharp

It should have private fields, public properties, constructors, public methods and private methods.

The dropdowns on the top beneath the tabs are going to help you find a specific member in a specific type. The left dropdown will show you different types in that file you are looking at. The second dropdown on the right will show you the different members that belong to the type you have selected in the left dropdown.

Use the search box on the top to look for anything in the selection/current file/current project/Entire solution. You can use replace option on the search window to replace a particular word(s).

You can right click on any method call or property and go to it’s definition. This is an important and useful functionlaity.

Find all References: You can select this from the right click options on any word in the code. It shows every place where the selected item is used within your code even if it is not on the same class.

Object Oriented ProgrammingC# is an Object oriented programming language. In our previous chapters we have discussed the simple definition of class as a collection of methods. Now, it’s time to expand that definition including fields, properties, methods which we are going to discuss now.

Classes are blue prints to create new instances of objects.

OOPs is nothing but a way or an approach to simplify the task of building software.

OOPs helps you write programs that are easily maintainable and help us re-use code. If you write a class in one application, you can use it in other applications to perform the same functionality without re-writing it.

Think of a class as a car and all the things like model, make, year, color, miles and speed as its fields. We do not know what goes on in the background when we accelerate. What all we have is a peddle to speed up the car which is the interface to do so. This is nothing but encapsulation.

Encapsulation It is the process of keeping the details of an implementation of an object as private. It enforces “Black Box” programming. Changes to the code in the black box (interface) should not affect the interface. Let’s see how to implement the encapsulation using Methods, Fields and Properties.

Class is nothing but a blue print that defines it’s fields, methods and properties.

Below is the code that needs to be added in Car.cs file.

Page 50: CSharp

Below is the code that needs to be added in Program.cs file

Page 51: CSharp

Methods, Fields and Properties

MethodsIn our previous discussions, we mentioned that the methods are a block of code and that has a name. In the Car.cs file we created our own methods and named them as Accelerate() and Deccelrate().

Methods can accept parameters and return a value.

IN the Accelerate() method we have defined it in such a way that it does not accept any parameters Z(because we mentioned nothing in the parenthesis) and does not return any values (because we have void in front of it).

NOTE: Keyword void means that the method is not going to return any value.

RETURNING A VALUE FROM A METHOD

Now, look at the following code. We have changed the Accelerate method to return a value of type int. Below is how it looks like.

We use the keyword return to return a value from a method.

ACCEPTING PARAMETERS IN A METHOD:

Look at the following code, to see how we have modified the Accelerate() method to accept a parameter.

In line 16, we have changed the method signature to accept a parameter of data type int. In line 18, we are making use of the passed in parameter value to add it up to the speed. The operator += means add the value of the left hand side variable to the one on the right and assign it to the variable on the left hand side. In the case of line 18, it can also be written as

Speed = Speed + incrementBy;

Page 52: CSharp

So, wherever you call this method of Car class, you need to pass in an integer value in the parenthesis (for proper functioning of the method and to avoid the build errors).

METHOD HEADER

The entire definition as shown below from Accelerate method is called Method Header. Header includes the data types and the names of the parameters.

public int Accelerate(int increaseBy)

METHOD SIGNATURE

Signature includes only the data types.

public int Accelerate(int)

Fields and PropertiesFields define the state or attributes of an object. The attributes like speed, model, make in car can be treated as fields. If you look at the car class, we have defined speed, model, make, year and color. They are nothing but Fields of the class called car.

Never give the access to fields in a class as it could cause potential threat to the stability of an object. Instead, we can add a layer on top of it to protect the field. This layer is called as property. In order not to make the field accessible by the user we have to make it private. For instance, let’s consider the field we already have in car class.

public int Speed;

We can make this not accessible by program.cs by changing this line of code in car.cs to something like this.

private int speed; //lower case letter to begin with

NOTE: The common naming convention is to start the variable name with a lower case whenever it is private and start with Upper case when public.

NOTE2: After changing the field, if you try to access this field from program.cs file you won’t be able to see this in the intellisense and cannot access it because it is protected to be used just in car.cs file. Private and public are called as access modifiers which will be discusses later.

Now, to add a layer on top of this field in order to protect it we can add a property. You can think of a Property like a special kind of method that has two sub methods in it. One sub method for setting (assigning ) a value to the field for which the property is being built on top. One for getting or accessing the value of the field. Below is how a property looks like for the field speed.

Page 53: CSharp

Another advantage of properties over fields is that you can change their internal implementation without breaking the code (or changing the interface of the object). With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation. You can also do validations on the values that are being set to a field through property.

Auto-implemented PropertiesThese are used to reduce the amount of coding. See below for the property called Speed. We are not doing anything except wrapping the field speed so as to give users the access to it through this property.

These can also be written as

Instantiation of a class with a new operatorThe steps taken to create a new instance of a class is called as instantiation. The new operator is used to instantiate a class. See below for the way we instantiate car class.

Car c; c = new Car();

In line of the code, we are creating a pointer to the object of type Car. c is called as a reference variable that holds the pointer to the object.

Page 54: CSharp

We followed the same way of instantiation while talking about DateTime datatype and its ways of instantiation.

There are two ways the .net runtime uses the computer’s memory. It organizes some of it into an area called stack and some of it into Heap. Stack is an organized grouping of information and heap is an unorganized way of putting the things. Stack is where the value types of integer and other simple types are stored. Stack is organized and easy for the application to find what it is looking for because it knows the exact size of each of those objects and they are typically small in size. Heap is where reference types like string object, datetime object, custom objects are stored. Since this information varies and typically much larger they are piled in the heap wherever they gonna fit and is accessed through an address. So, the only way to keep track of memory is then through the reference.

Stack Heap

1 organized grouping of information unorganized grouping of information

2 Stack is where the value types of integer and other simple types are stored

Heap is where reference types like string object, datetime object, custom objects are stored

3 Stack is organized and easy for the application to find what it is looking for because it knows the exact size of each of those objects and they are typically small in size

Since this information varies and typically much larger they are piled in the heap wherever they gonna fit and is accessed through an address

4

Reference variable stores the address/pointer to the memory location of an object in memory. This reference variable is stored in the stack which holds the value of the pointer to the object that is stored in the heap. In order to store the things efficiently this is the system they came up with.

Page 55: CSharp

A single reference variable can only hold a pointer to a single object in memory. When the object has no references to it, it is removed from the memory by .NET framework runtime using Garbage Collector. Look at the below example.

Please read through the comments for better understanding of the code.

Now that we have talked about the new operator and what does it do, let’s talk about the parenthesis that are at the end of the instantiation of an object. In the case of Car c = new Car(); there are () at the end of the statement. The reason for that is because, when we create a new instance of a class we are implicitly calling a method in the class called “Constructor”. Constructor method gives us the chance to initialize the class immediately before we use it.

If we look at our Car class, we don’t see any constructor method other than the normal methods that we have created.s

InheritanceIn the previous session we have dealt with a class called Car which kind of represents the actual car in the real life. The cars of many types which includes trucks. The Sedan are same like cars but they can have moonroof, different number of seats (4 in this case), different type of seats (may be leather) etc.

Now, if you want to write a class defining all the properties and fields for truck then you go two choices. One is to define a class called sedan and copy and paste all the properties and fields from car as they would apply to sedan as well and define sedan’s own properties like seats. Second way is to inherit Sedan from Car class. Always use the second method to define such classes.

To inherit you have to specify the class you are inheriting from on the right hand side of the : after the Sedan class.

Page 56: CSharp

Now when you try to use the Sedan class in the program.cs file you can see that after initialization of this class you could access the public properties and methods from Car class.

In this case Car class is called as base class or parent class and Sedan class is called as derived class or child class. It is also referred to as generalization and the specialization.

This makes maintenance easy because you were able to list all the common properties/attributes in one class (Car class). If you ever need to add a property to all the derived classes you can just add it to the base class.

Overriding Methods and PropertiesYou can also override the base class’s methods or properties in the derived class.

You have to virtual and Override keywords to override a base class method in derived class.

Car class

Page 57: CSharp

Sedan Class

Page 58: CSharp

You can also use the new keyword in the derived class method but will talk about it in the polymorphism.

The overridden method (Repair()) will be used when the called from the instance of Sedan class instead of base class’s Repair method.

If you want to execute the base class’s Repair method also when you call the Sedan’s Repair method then you can use base.Repair() inside the overridden Repair() of senda class. See screenshot below. This way when you call Repair() in Sedan class then Repair() of Car class will also get executed.

Page 59: CSharp

ConstructorsAs we discussed in our earlier sessions while using new keyword to initialize an instance of a class we learnt that a method called constructor is getting called behind the scenes.

Car c = new Car();

Every class that we crete will be inherited from a base class called object and the System.Object defines a default constructor (that is why even though we have not defined any constructor in the Car class we were still able to use it) which is a special kind of method that automatically is called each time we call the new operator. It is used for intiializing the object to get the object into it’s right state before starting to use it.

We can override the base constructor by writing our own constructor in the Car class.

Constructor has the same name as the class name. Even though there is not a return value defined in the constructor it is implied that it is always void.

Overloading Methods and ContructorsIt allows the programmer do define several methods with the same name, as long as they take a different set of parameters. Method signatures would be different but the method name would be same.

Method overloading will be used to provide different methods that do semantically same thing. It is used instead of allowing default arguments. Use a consistent ordering and naming pattern for method parameters. It is common to provide a set of overloaded methods with an increasing number of parameters to allow the developer to specify a desired level of information.

If you must provide the ability to override a method, make only the most complete overload virtual and define the other operations in terms of it.

Same way you can also overload constructors to initialize differently.

AbstractThe abstract modifier can be used with classes, methods, properties, indexers, and events.

Page 60: CSharp

Use with ClassesUse the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.

Abstract classes have the following features:

An abstract class cannot be instantiated. An abstract class may contain abstract methods and accessors.

You cannot use abstract class with sealed modifier because it will be of no use.

A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

Use with Methods

Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.

virtual

The virtual keyword to specify that a member can be overridable. The implementation of a virtual member can be changed by an overriding member in a derived class.

When a virtual method is invoked (called), the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

Abstract methods have the following features:

An abstract method is implicitly a virtual method. Abstract method declarations are only permitted in abstract classes.

Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:

public abstract void MyMethod(); The implementation is provided by an overriding method, which is a member of a non-abstract

class. It is an error to use the static or virtual modifiers in an abstract method declaration.

Use with Properties

Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.

It is an error to use the abstract modifier on a static property.

Page 61: CSharp

An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

An abstract class must provide implementation for all interface members.

An abstract class that implements an interface might map the interface methods onto abstract methods. For example:

interface I { void M(); } abstract class C : I { public abstract void M(); }

Interface

An interface contains only the signatures of methods, delegates or events. We will be talking about delegates and events in the later sections. The implementation of the methods is done in the class that implements the interface, as shown in the following example:

interface ISampleInterface { void SampleMethod(); }

class ImplementationClass : ISampleInterface { // Explicit interface member implementation: void ISampleInterface.SampleMethod() { // Method implementation. }

static void Main() { // Declare an interface instance. ISampleInterface obj = new ImplementationClass();

// Call the member. obj.SampleMethod(); } }

An interface can be a member of a namespace or a class, It can contain signatures of the following members:

1. Methods

Page 62: CSharp

2. Properties

3. Indexers

4. Events

An interface can inherit from one or more base interfaces.

When a class is derived from both base calss and interface, the base class should always be listed first followed by the interfaces. See below

Class Student : Person, IHuman

Differences between Interfaces and abstract classesFeature Interface Abstract class

Multiple inheritance A class may inherit several interfaces.

A class may inherit only one abstract class.

Default implementation An interface cannot provide any code, just the headers.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modifiers An interface cannot have access modifiers for the methods and properties. Everything is assumed as public

An abstract class can contain access modifiers

Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

HomogeneityIf various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed Requires more time to find the actual method in the corresponding classes.

Fast

Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define

If we add a new method to an abstract class then we have the option of providing default implementation and therefore

Page 63: CSharp

implementation for the new method.

all the existing code might work properly.

Fields and ConstantsNo fields can be defined in interfaces

An abstract class can have fields and constants defined

sealedA sealed class cannot be inherited. It is an error to use a sealed class as a base class. Use the sealed modifier in a class declaration to prevent inheritance of the class.

It is not permitted to use the abstract modifier with a sealed class.

Structs are implicitly sealed; therefore, they cannot be inherited.

// Sealed classes sealed class MyClass { public int x; public int y; }

class MainClass { public static void Main() { MyClass mC = new MyClass(); mC.x = 110; mC.y = 150; Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); } }

staticUse the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors.

A static member cannot be referenced through an instance. Instead, it is referenced through the type name. For example, consider the following class:

public static class MyMath { public static int Add(int a, int b) { return a + b; } } To refer to the static member Add, use the fully qualified name (if you don’t use using statement):

Page 64: CSharp

MyMath.Add(10, 20); (fully qualified name means including the namespace infront of the class name)

While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.

It is not possible to use this to reference static methods or property accessors.

Access Modifiers We have already talked about private and public in the previous examples. There are two more, protected and internal.

NOTE: Camel casing is preferred for private variables and Pascal casing (starting with capital letter) is preferred for public variables. Some programmers also use _ (underscore) in front of private variables (fields) but that’s more of VB convention. So, prefer camel casing for such variables.

If you make a field or property as private, then it cannot be accessed from outside the class. For instance, if you change the Make field to private in the Car.cs class file, and if you try to access it from program.cs file you cannot access it.

Not just for fields and properties, the access modifiers can also be applied to methods. We use the private methods more for refactoring our code or as helper methods in the class files.

Modifier Description

Public There are no restrictions on accessing public members.

Private Access is limited to within the class definition. This is the default access modifier type if none is formally specified

Protected Access is limited to within the class definition and any class that inherits from the class

Internal Access is limited exclusively to classes defined within the current project assembly

protected internal Access is limited to the current assembly and types derived from the containing class. All members in current project and all members in derived class can access the variables.

Page 65: CSharp

Arrays and Collection of Objects

Arrays of ObjectsJust like we use Arrays to work with value types like int and string they can also be used to work with Custom types. For instance let’s do an array of our custom type Sedan. Below is how we defined the array of strings.

We’ll follow the same way to define the array of custom type Sedan.

Page 66: CSharp

Below is the output for the above program.

There are disadvantages in using Array for collection of custom types.

1. You need to know how many items you need to be in the array to begin with. You cannot dynamically add the items to this array as it would throw “the out of range” exception.

Page 67: CSharp

2. You cannot remove an item from the array because the array should be of the size mentioned while declaring it.

So, using Arrays of objects is of limited use.

ArrayListTo overcome the above problems, we can use ArrayList. Below is how we would initialize an ArrayList.

Page 68: CSharp

Notice that we have added a using statement on the top of the file in line 6 using System.Collections; to make use of all the classes from that namespace. The class that we are going to make use form System.Collections is ArrayList.

In line 16, we have initialized an ArrayList called Sedans. Please go through the comments for better understanding.

Following line 16 through line 31, we have done the same thing as we did in the case of Array. We are initializing the objects before we add it to the Array/ArrayList.

In line 34, we are using a method called Add from ArrayList class to add the object (in our case Sedan object) to the arraylist. Instead of assigning it at a specific index in case of Array we are just adding it to the ArrayList here.

In line 42, instead of for loop we have to use foreach loop to loop through each of the object (in our case Sedan) of the ArrayList. You can do a for loop also but you have to cast the object to Sedan type before trying to take advantage of the item. Try the for loop as an exercise and produce the same result.

This code will produce the same result as in the case of array.

Using the ArrayList you can add any number of items dynamically. Look at below code.

Not only adding the items dynamically, you can also specify where to add in the collection (at which number/index). See below to add the sedan4 at position 2.

In the above code, Commented out line 54 as we do not want to just add but to specify the position where we want to add the item sedan4. We use Insert method of ArrayList class which takes the parameters of index of type int and object. We specified it to be on index 1.

Not just adding it at specific location, you can also remove it from a specific location. See below.

Page 69: CSharp

The above code, removes the item at the index 1 (which is nothing but the one that we have added a moment ago sedan4).

Not just by specifying the index, you can also remove the item by calling the Remove method which accepts the object (item). See below to remove the sedan4 object.

While coding for a specific business purpose you might come across removing the items from the arraylist if it does not satisfy a condition. You can loop though items and remove them from the arraylist if it does not satisfy a specific condition.

Not just the objects of type Sedan can be added to the arraylist Sedans but also other custom types (for example Coupe or any other you would write) because the Add method of arraylist would expect an object. While looping through you would have to cast the object to find out which one it is you are trying to access the item.

Exercise: Add a class called Coupe with some properties and Accelrate(int) method. Instantiate it in the program.cs file and Add that to the ArrayList of Sedans. Loop through all the items in the list and call the same Accelerate(int) method.

The advantages of using ArrayList over Array are

1. you do not have to specify the number of items you are going to add to the arraylist (where in the case of you would have to mention it while declaring).

2. You can easily remove or add the objects dynamically.3. You can insert items at a specific position.

The disadvantages of ArrayList

1. It is a bit cumbersome because everything in the collection will be saved as type System.Object. So, when we get the item out of collection we have to cast it back to the custom type before start using the item. It can break the code if you add any type of the custom objects because you have to cast the items.

Generic CollectionsIn order to overcome the problems with ArrayList, in .NET v2.0 Generic collections was introduced.

Every item in the collection is guaranteed to be the exact same type. There is no chance of having two objects of different custom types in the same collection because we will be specifying which custom type this collection will be of. This gives us type safety. Any time the strongly typed code will give us more robust output and prevent any errors in the compile time.

Page 70: CSharp

Below is the code block describing the way of writing a generic Collection.

Line 17 is how you would declare a List of specific type called Sedan. We would have to define the specific type in <> brackets. As soon as you type List< in the program it would give you the tooltip like below

T means any Type. Here we are specifying the type as Sedan (line 17).

Page 71: CSharp

From line 19 through 32 we are initializing various instances of Sedan object so as to add them to the Sedans list. When you try to add an item to the Sedan list it would show you a tooltip like below asking you to input an item of type Sedan (as the list was declared as a type of Sedan) where as in the case of ArrayList it was expecting an object of any type.

Page 72: CSharp

In the foreach loop you would know what type you are exactly dealing with but where as in the foreach loop of ArrayList you have cast the type because you don’t know what type of object will be in the collection.

Now, when you try to add the instance of class Coupe to this list of Sedans it will not let you do that and through the errors while compiling. There is a way to do this using the Generics but you will learn that in the next session.

Polymorphism via InheritancePolymorphism is another primary concept of OOPs. It allows you to invoke derived class methods through a base class reference during run-time.

It is the ability of the code to act like many different things but still be treated the same. To understand the polymorphism more clearly first make sure you follow these three classes Car, Sedan and Coupe.

Car.cs

class Car { //Class public class Owner { private string fullName; public string FullName { get { return fullName; } set { fullName = value; } } }

//properties public Owner Customer = new Owner(); public string Make { get; set; } public int Year { get; set; } public Engine CarEngine { get; set; } public int Speed { get; set; }

Page 73: CSharp

//constructor public Car() { //initialize the important stuff }

//overloaded constructor public Car(int _speed) { //sometimes underscores are used //to differentiate between the pased in parameter and property/field Speed = _speed; }

//Methods public virtual void Accelerate(int increaseBy) { Speed += increaseBy; }

public virtual void Repair() { Console.WriteLine("Repairing..."); } }

Sedan.cs

class Sedan : Car { //properties public int Seats { get; set; } //Methods public override void Accelerate(int increaseBy) { base.Accelerate(increaseBy); } public void OpenMoonRoof() { Console.WriteLine("opening the moon roof..."); }

public override void Repair() { base.Repair(); Console.WriteLine("Repairing Sedan..."); } }

Coupe.cs

class Coupe : Car {

Page 74: CSharp

//properties public int Doors { get; set; }

//contructor public Coupe() { }

//methods public override void Accelerate(int increaseBy) { base.Speed += increaseBy; } }

Car calss is a base class and Sedan, Coupe are derived from it. Remmebr that all the properties, fields and methods of base class can be accessed by the derived class. Accelerate(int) is a virtual method in th ebase class and it is overriden in both the derived classes.

While coding the List of Sedans, we had a doubt whether we can add the objects of two different types to the List of specific type (in our case Sedan). Yes it is possible by using the inheritance concept. If we specify the type as base class then we can add n number of derived types to the list of base type. See below for the illustration.

Page 75: CSharp

In line 14, you have declared a list of type Car. In line 16 through 20 you have instantiated a Sedan object and assigned some values to its properties. In line 22 through 26 you have instantiated a Sedan object and assigned some values to its properties.

When you look at line 28, as soon as you type cars.Add( it would prompt you with a tooltip help asking you to enter the object of type Car (see below).

But, you have entered sedan1 which is of type Sedan and not Car. It still accepts it without throwing any compile time/run time errors. The reason is because the sedan class is derived from Car class and while declaring the list of cars we are telling that as long as that we are trying to add an item that is related to car accept it.

So we were able to add the two different types to the same collection of objects by making them inherit from the base class and then using the generic collection of base class type (car) in order to treat them all equally. And as long as we are not using the specific form of it we can get this polymorphic behavior.

But, what if we don’t want to supply an implementation of Accelerate(int) in the base class. What if we want to require any derived class must implement Accelerate(int) and we don’t want to force any specific implementation. (In other words, we don’t want speed to be increaseby the passed in value in the base class). The answer is by using abstract classes.

Polymorphism via Abstract Class

As discussed earlier, Abstract classes provide no base implementation of a given method, relying solely on the derived classes to supply an implementation of the method.

Abstract is just like a regular class except that it can define method headers without defining the body of those method headers which forces all derived classes to implement that method without the base class implementing it’s own version. When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract . If all the methods of an abstract class are uncompleted then it is same as an interface.

Please take a look at the Car class that has been changed to abstract class (removing some unnecessary properties and members for simplicity sake).

Below are main points about abstract classes

1. It cannot be instantiated2. It can only be inherited by the other classes

Page 76: CSharp

3. It forces some standards for all the derived classes4. A class can be derived from only 1 abstract class

Car.cs

abstract class Car { //properties public string Make { get; set; } public int Year { get; set; } public Engine CarEngine { get; set; } public int Speed { get; set; }

public abstract void Accelerate(int increaseBy); }

With this change in the base class, nothing needs to be changed in the derived classes. Override keyword on Accelerat(int) method in derived classes is still should be same.

If you execute the same code in program.cs file the result would be same.

This is one more way of implementing polymorphism using abstract classes and the first one by using inheritance.

What if both Sedan and Coupe are different types and not related at all or not derived from same base class? Can we still work with them polymorphically? Yes, it is possible through Interfaces.

Polymorphism via InterfacesAn interface just looks like a class but it has no implementation. It contains declarations of events, indexers, methods and/or properties. The classes that inherit the interfaces must provide an implementation for each interface member declared.

It is a contract, when a class implements an interface then it should implement all the methods and properties defined in the interface.

Below are main points about Interfaces

1. It is not a class but an entity defined by a keyword interface2. It has no implementation but just have the headers.3. It is a contract that is used to define the standards for all the sub classes (just like abstract class)4. A class can implement multiple interfaces

Let’s look at interfaces in System.Collections.

Collections that support Sorting and ordering, they implement IComparable interface. Collections that support iterations, implements IEnumerable Collections that support indexing (like ArrayList and List) implement IList interface

Page 77: CSharp

Interfaces help in making the code more flexible.

For instance consider the below interface ICar. (Start the interface name with I to differentiate it from normal classes. It is a best practice.)

interface ICar { string Make { get; set; } int Year { get; set; }

void Accelerate(int increaseBy); }

When Sedan or Coupe classes inherit this interface they must implement the above properties and method. If they don’t, then compiler is not going to let the program build.

The code we used in the program.cs to demonstrate the abstract classes is still valid but with a small change. Instead of List<Car> cars = new List<Car>(); you have to do List<ICar> cars = new List<ICar>(); and in the foreach loop instead of declaring Car now declare ICar because the list is of ICar. The rest of the code can remain same. In this code even though we are defining the list as a collection of ICar it would accept Sedan and Coupe instances to be added to the list as they have implemented this ICar interface.

NOTE: Try to use interfaces to pass in as parameters to the methods and return values from methods if they are other than value types (int, string, bool). It is a best practice followed by high end programmers.

Note: While programming, use IDE to implement the interface for a class. See below.

Note: You can define regions to organize your code in a better way.

Association of the ObjectsThere are two basic types of associations (relationships).

1. Aggregation2. Containment/Composition

AggregationSo far, we have used simple data types to express the fields, properties and methods (to return values) in the classes. Whenever we are building classes, we are building custom reference types just like .NET reference types. We can use reference types to define new fields and properties and to return values for

Page 78: CSharp

methods and accepting parameters using these custom types. We may not just use string or int but we can also use a reference type Car.

To begin with, let’s start adding a manufactured date fields and property to the Car.cs.

Here DateTime is a reference type from .NET and we are using it in the same way as int and string. Now, to use this property in the program.cs file, this is how you would do.

In line 12, you have initialized an object of type Car using the new keyword and the variable that holds the pointer to that object is called as c.

In line 15, we are declaring and initializing a variable dt of type DateTime.

In line 21, we are accessing the property ManufacturedDate and setting its value to dt.

In line 25, we are trying to see what is there in the DayOfWeek of ManufacturedDate property of c.

Page 79: CSharp

NOTE: ManufacturedDate is nothing but a reference to the actual DateTime object stored on the heap.

This type of relation between the car object and datetime object is called Aggregation (combination).

Example:

1. Add a class called Engine and define some properties in it. Add a property called CarEngine of reference Type Engine to the class Car. Make use of this Engine property in the program.cs file.

2. Create one more class called Factory and create a method that does the following.a. Returns an instance of Car classb. Accepts datetime variable of type DateTime. Set this value to the ManufacturedDate property of the

instantiated Car class.

Containment/CompositionDefining a class with in a class is called containment. The custom type or class definitions can be embedded inside of other type definitions indicating that the relationship is containment (or ownership).

Example: Define a class called Customer in the Car class and use it in the program.cs file.

Page 80: CSharp

Below is how we access the CarCustomer in program.cs file.

Page 81: CSharp

EnumerationsEnumeration is a special kind of type that only has certain values defined as possible values.

Console.ForegroundColor = ConsoleColor.Blue;

Consider the above line of code where we are setting the console window foreground color. Instead of specifying the color as a string we have set it from a type called ConsolColor because that is what is the type of ForgroundColor property. This would limit the values to be set to the property.

Define an enum called SeatType with Leather, Cloth as values and define a property called CarSeatType in the Car class of type SeatType.

Below is how we would define the enum under the same namespace as the Car.

enum SeatType { Leather = 1, Cloth = 2 }

IN the car class below is how we would define the property (remember this is a auto implemented property)

public SeatType CarSeatType { get; set; }

Now, when you try to access this property in the program.cs file then you can set the value of the CarSeatType property only from the two values listed in the enumerator.

The benefit of this approach is that it is strongly typed.

Weakly typed means that invalid values can’t be checked at compile time due to the use of strings. Strongly typed means that invalid values will be checked and compiler won’t compile if the value is not set correctly.

Page 82: CSharp

Value TypesThe value types consist of two main categories:

Structs

Enumerations

Structs fall into these categories:

Numeric types o Integral types

o Floating-point types

o decimal

bool

User defined structs.

Main Features of Value Types

Variables that are based on value types directly contain values. Assigning one value type variable to another copies the contained value. This differs from the

assignment of reference type variables, which copies a reference to the object but not the object itself.

All value types are derived implicitly from the System.ValueType.

Unlike with reference types, you cannot derive a new type from a value type.

Like reference types, structs can implement interfaces.

Unlike reference types, a value type cannot contain the null value. However, the nullable types feature does allow for values types to be assigned to null.

o Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value.

Each value type has an implicit default constructor that initializes the default value of that type. For information about default values of value types, see below for the Default Values Table.

Page 83: CSharp

struct

A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:

public struct Book { public decimal price; public string title; public string author;

}

Page 84: CSharp

Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead.

Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.

ConstantsConstants are immutable (changeless) values which are known at compile time and do not change for the life of the program. Constants are declared with the const modifier.

Casting

Converting between data types can be done explicitly using a cast, but in some cases, implicit conversions are allowed. For example:

static void TestCasting(){ int i = 10; float f = 0; f = i; // An implicit conversion, no data will be lost. f = 0.5F; i = (int)f; // An explicit conversion. Information will be lost.}

A cast explicitly invokes the conversion operator from one type to another. The cast will fail if no such conversion operator is defined. You can write custom conversion operators to convert between user-defined types.

Boxing and Unboxing

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.

In the following example, the integer variable i is boxed and assigned to object o.

int i = 123;// The following line boxes i.object o = i;

Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system, in which a value of any type can be treated as an object.

The object o can then be unboxed and assigned to integer variable i:

Page 85: CSharp

o = 123;i = (int)o; // unboxing

Object and Collection InitializersObject initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The following example shows how to use an object initializer with a named type, Cat. Note the use of auto-implemented properties in the Cat class.

class Cat { // Auto-implemented properties. public int Age { get; set; } public string Name { get; set; } }

Here is the way you can initialize the Cat object

Cat cat = new Cat { Age = 10, Name = "Fluffy" };

Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

The following examples shows two simple collection initializers:

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<int> digits2 = new List<int> { 0 + 1, 12 % 3, MakeInt() };

The following collection initializer uses object initializers to initialize objects of the Cat class defined in a previous example. Note that the individual object initializers are enclosed in braces and separated by commas.

List<Cat> cats = new List<Cat> { new Cat(){ Name = "Sylvester", Age=8 }, new Cat(){ Name = "Whiskers", Age=2 }, new Cat(){ Name = "Sasha", Age=14 } };

You can specify null as an element in a collection initializer if the collection's Add method allows it.

List<Cat> moreCats = new List<Cat> { new Cat(){ Name = "Furrytail", Age=5 }, new Cat(){ Name = "Peaches", Age=4 }, null };

Page 86: CSharp

Exception handlingIn every program, things go wrong sometimes. With C#, we're blessed with a good compiler, which will help us prevent some of the most common mistakes. Obviously it can't see every error that might happen, and in those cases, the .NET framework will throw an exception, to tell us that something went wrong. In an earlier chapter, about arrays, I described how we would get an exception if we tried to stuff too many items into an array. Let's bring the example:

using System;

using System.Collections;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

int[] numbers = new int[2];

numbers[0] = 23;

numbers[1] = 32;

numbers[2] = 42;

foreach(int i in numbers)

Console.WriteLine(i);

Console.ReadLine();

}

}

}

Page 87: CSharp

Okay, try running this example, and you will see what I'm talking about. Do you see what we're doing wrong? We have defined an array of integers with room for 2 items, yet we try to use 3 spaces in it. Obviously, this leads to an error, which you will see if you try to run this example. When run inside Visual C# Express, the IDE gives us some options for the exception, but if you try to execute the program by simply doubleclicking the EXE file, you will get a nasty error. If you know that an error might occur, you should handle it. This is where exceptions are used. Here is a slightly modified version of the code from above:

int[] numbers = new int[2];

try

{

numbers[0] = 23;

numbers[1] = 32;

numbers[2] = 42;

foreach(int i in numbers)

Console.WriteLine(i);

}

catch

{

Console.WriteLine("Something went wrong!");

}

Console.ReadLine();

Let me introduce to you your new best friend when it comes to error handling: the try..catch block. Try running the program now, and see the difference - instead of Visual C# Express/Windows telling us that a serious problem occured, we get to tell our own story. But wouldn't it be nice if we could tell what went wrong? No problem:

catch(Exception ex)

{

Page 88: CSharp

Console.WriteLine("An error occured: " + ex.Message);

}

As you can see, we have added something to the catch statement. We now tell which exception we want caught, in this case the base of all exceptions, the Exception. By doing so, we get some information about the problem which caused the exception, and by outputting the Message property, we get an understandable description of the problem.

As I said, Exception is the most general type of exception. The rules of exception handling tells us that we should always use the least general type of exception, and in this case, we actually know the exact type of exception generated by our code. How? Because Visual Studio told us when we didn't handle it. If you're in doubt, the documentation usually describes which exception(s) a method may throw. Another way of finding out is using the Exception class to tell us - change the output line to this:

Console.WriteLine("An error occured: " + ex.GetType().ToString());

The result is, as expected, IndexOutOfRangeException. We should therefore handle this exception, but nothing prevents us from handling more than one exception. In some situations you might wish to do different things, depending on which exception was thrown. Simply change our catch block to the following:

catch(IndexOutOfRangeException ex)

{

Console.WriteLine("An index was out of range!");

}

catch(Exception ex)

{

Console.WriteLine("Some sort of error occured: " + ex.Message);

}

As you can see, we look for the IndexOutOfRangeException first. If we did it the other way around, the catch block with the Exception class would get it, because all exceptions derive from it. So in other words, you should use the most specific exceptions first.

One more thing you should know about concerning exceptions is the finally block. The finally block can be added to a set of catch blocks, or be used exclusively, depending on your needs. The code within the finally block is always run - exception or no exception. It's a good place if you need to close file references or dispose objects you won't need anymore. Since our examples have been pretty simple so far, we haven't really been in need of any cleanup, since the garbage collector handles that. But since

Page 89: CSharp

will likely run into situations where you need the finally block, here is an extended version of our example:

int[] numbers = new int[2];

try

{

numbers[0] = 23;

numbers[1] = 32;

numbers[2] = 42;

foreach(int i in numbers)

Console.WriteLine(i);

}

catch(IndexOutOfRangeException ex)

{

Console.WriteLine("An index was out of range!");

}

catch(Exception ex)

{

Console.WriteLine("Some sort of error occured: " + ex.Message);

}

finally

{

Console.WriteLine("It's the end of our try block. Time to clean up!");

}

Console.ReadLine();

Page 90: CSharp

If you run the code, you will see that both the first exception block and the finally block is executed. If you remove the line that adds the number 42 to the array, you will see that only the finally block is reached.

Another important part you should know about exceptions, is how they impact the method in which the exceptions occur. Not all unhandled exceptions are fatal for your application, but when they aren't, you should not expect the remaining code of the method to be executed. On the other hand, if you do handle the exception, only the lines after the try block will be executed. In our example, the loop that outputs the values of the array is never reached, because the try block goes straight to the catch/finally block(s) once an exception is thrown. However, the last line, where we read from the console to prevent the application from exiting immediately, is reached. You should always have this in mind when you construct try blocks.

Introduction to UML and Class Diagrams

In this chapter you’ll learn the basic (Unified Modeling Language) UML class diagrams.

UML is a method of explaining the approach.

The class diagram will help you in illustrating the particular attributes and methods of a given class. It also gives us the relationship between the classes with in the application.

Consider the class below in the screenshot and we’ll see how this class is represented using the UML.

Page 91: CSharp

A Class is represented usually as a rectangle having three components.

1. Class Name2. Properties and Fields3. Methods

While representing the Car class below is how it is defined.

Notice the (Minus) - sign before speed. It indicates that it is a private member.

(Plus) + sign indicates that the member is a public member.

In the third compartment, notice the + sign indicates the method as public. Notice that it defines a parameter “increaseBy” of type integer. So, between the parenthesis we defined the parameter. If we

Page 92: CSharp

have multiple parameters, we define them by separating with comma. At the end you can see int which means that the method returns the type int.

NOTE: You can give the UML defined to some developer and ask him to develop the class file for you.

Relationships in UML

Aggregation RelationshipIn one of the examples while describing the Aggregation and Component concepts, we have defined a class called Engine and used it in the Car class as a property. The same can be represented using the UML in the following manner.

Look at the below screenshot which has the CarEngine property which is referencing the type Engine.

Page 93: CSharp

So, below is how we indicate the relationship between the Car and the Engine.

Relationship can be denoted with a single line and use the arrow at the end of the line to denote the direction of the relationship. IN this case, the Car holds the reference to Engine. The name of that

Page 94: CSharp

reference can be added on top of the arrow (in our case it is called CarEngine). Number 1 on the top is to know the number of instances held by the relationship. In this case, Car will hold one reference to an Engine and will reference that Engine using CarEngine Property.

Containment or Composition Relationship

Look at the example we have built while defining the Containment type of classes.

Page 95: CSharp

This kind of relationship is shown as below. Diamond at the beginning of the line represents the Car owns/has a Customer.

Page 96: CSharp

These type of diagrams are useful while explaining the design intent or architecture. Can be used to explain how are classes should be structured and how we want them to interact with out writing any code.

Static and InheritanceStatic class is expressed same as the normal class but the difference is there will be an underline for each static member and even the class name. The underline denotes that it is a static member.

Inheritance between Sedan and Car classes are shown as below.

Page 97: CSharp

The inheritance is denoted by an arrow with an empty triangle at the end of the base class. The arrow denotes that the Sedan class is inherited from Car class. If there is an overridden method, in this case, Start(), it would be shown in both the classes.

Abstract Class/MethodsBelow is the way of showing abstract classes. A class is specified as an Abstract by writing abstract in the curly braces underneath the class name.

If in a normal class there is an abstract method, then we can denote it in two ways. One by writing in italic font. Second, is it will have {abstract} next to the method name.

Page 98: CSharp

Interface

There are two ways to show the interfaces in UML.

1. First way is to show as below. ICar is shown as an interface by using <<interface>> on top of the class name. Interface implementation relationship is shown by a dashed line with arrow head (empty triangular head) pointing to interface. All the methods inherited will be shown in the place where _Accelerate(int) is shown (please recollect from the earlier UML lessons on what does + sing mean).

2. Second way is shown as below. The interface is defined the same way as above. The Sedan class is implementing the Icar and is shown by using a Circle tied to the Sedan class by a line.

Page 99: CSharp

Recommended