L1: C# Classespeople.sutd.edu.sg/~ugur_arikan/Documents/Tutorials/CSharp/L1.pdf · L1: C# CLASSES...

28
L1: C# CLASSES 10/13/16 Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 1 L1: C# Classes This tutorial covers the basic topics on C# classes, class inheritance, user interface of a console application, array and list structures, and debugging options for the optimization models, algorithms and heuristics, and simulation models that will be created in the following tutorials. You can download and setup Visual Studio Community (free, fully-featured IDE for students, open- source and individual developers) using the following link: https://www.visualstudio.com/downloads/.

Transcript of L1: C# Classespeople.sutd.edu.sg/~ugur_arikan/Documents/Tutorials/CSharp/L1.pdf · L1: C# CLASSES...

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 1

L1: C# Classes

This tutorial covers the basic topics on C# classes, class inheritance, user interface of a console

application, array and list structures, and debugging options for the optimization models,

algorithms and heuristics, and simulation models that will be created in the following tutorials.

You can download and setup Visual Studio Community (free, fully-featured IDE for students, open-

source and individual developers) using the following link:

https://www.visualstudio.com/downloads/.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 2

STEP 1:

Your program will be crated with a single class, Program.cs.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 3

If you do not see the Solution Explorer in the left panel, click View > Solution Explorer.

To build your program, click Build > Build Solution (or Ctrl + Shift + B). Output window will

appear and show you the warnings or errors of your code.

To run your program, press the Start button (or F5). You will see a console appear and

disappear quickly.

If you do not want the console to close at the end, press Ctrl + F5. Since the code doesn’t write

anything to the console yet, you will not see anything.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 4

2.1 Writing to Console

STEP 2:

Add the following code in the Main function of the Program.cs,

and Ctrl + F5.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 5

2.2 Reading from Console

STEP 3:

Add the following code in the Main function of the Program.cs,

and Ctrl + F5.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 6

In the lines starting with string and double, we define variables with these types.

In the lines with Console.ReadLine(), we read the user input into these variables.

Lines with Convert.ToDouble method converts string to double to be able to make the

multiplication operation.

In order to check other type conversions, type Convert. and check the dropdown list:

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 7

STEP 4:

Right click L1 in the Solution Explorer; and click Add > Class.

Change the class name as Person.cs and click Add. Your class will be added in the Solution

Explorer.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 8

3.1 Class Fields

STEP 5:

Add the following fields to be stored for Person class.

The keyword private means that these fields cannot be reached outside the class.

Alternatively, you can go with public to be able to reach them.

However, it is safer to go with private; and add public getters and setters whenever you need

them.

3.2 Class Constructors

STEP 6:

Add the following constructor.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 9

The keyword this refers to the object. Therefore, in the line

this.name = name;

the name in the left-hand-side is the name field of the object; and the name in the right-hand-

side is the argument of the constructor.

Note that the constructor is public and can be called outside the class to create Person objects.

Since the only constructor of the class requires three of the fields; in your program there cannot

exist a Person without these attributes set.

If you do not require some of these fields; you can drop from the required arguments.

For instance, if you have the following constructor:

public Person(string name)

{

this.name = name;

}

you may have Person objects without age and height assigned (actually they will take the default

values of int and double which are 0 and 0.0, respectively).

Therefore, the arguments required by the constructors are important for controlling that the

objects are created with the required fields.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 10

3.3 Class Methods

STEP 7:

Add the following methods.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 11

Four of the methods are public, so they can be called outside the class.

The first method simply returns the name of the object. string is the type of the value that will be

returned.

In the second method, the type void means that the method will not return any value. The method

requires a double argument and sets the height of the object to the argument.

The third method will increment the age of the object.

The last method returns a summary of the Person’s fields in string. Environment.NewLine is used

to add a line break.

Up to now, we can change the height and age of a Person object by public methods; but we are

sure that the name of a Person object will always be as it was created by (because there is no

public method to set the name).

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 12

3.4 Check the Class

Go back to Program.cs, clear the code within the Main method to check the Person class.

STEP 8:

Add the following code in the Main method of Program.cs.

and Ctrl + F5.

The lines with Console.WriteLine() is just to add a blank line.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 13

The first two lines create two Person objects with the constructor. Note that the name of the

object (the one on the left-hand-side) does not have to be the same with the name field of the

object (the one on the right-hand-side in quotes).

In the line with “name of the first …”, we call the public method getName() to get the name of

the object.

In the following two Console.WriteLine lines, we call the method toString() to get the summary

of the fields of the objects.

Next, we change the height of the first object by the setHeight method; and, we change the age

of the first object by the incrementAge method.

Then, we again call the toString() method to see the update.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 14

We will create a PhdStudent class which is also a Person.

In other words, a PhdStudent inherits all fields and methods of the Person class; but it will also

have other fields and methods.

STEP 9:

Create a new class named as PhdStudent (as in Step 4).

Add the following fields, constructor and methods.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 15

The inheritance is defined by

class PhdStudent : Person

In addition to the fields of Person, a PhdStudent object will have three additional fields.

The constructor requires four arguments. Three of them are the fields of the parent class. Among

the three new fields; the constructor requires only the pillar. This is because we assume that at

the beginning, the thesisTitle of a student is not known; and we certainly know that the

passedQual field is false. String.Empty is self-explanatory.

The line

: base(name, age, height)

calls the constructor of the Person which assigns the name, age and height of the object.

Whenever, the student decides on the thesis title, we will call the setThesisTitle method.

Whenever, the student passes the qual, we will call the passTheQual method. Note that there is

no way to assign the passedQual field back to false again, if this method is ever called.

The last method summaryString is similar to the toString method of Person. Note that it calls

the toString method of the parent class in order not to repeat the code.

Note also that the four methods of the Person class can be used by a PhdStudent object.

However, a Person object cannot use the methods of the PhdStudent class.

Finally note that without using inheritance; we could add the fields and methods of the Person

class to the PhdStudent; and get the same result. You will decide on when to use and not to use

inheritance depending on your project; but the idea is to avoid repeating any code.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 16

Go back to Program.cs, clear the code within the Main method to check the PhdStudent class.

STEP 10:

Add the following code in the Main method of Program.cs.

and Ctrl + F5.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 17

5.1 Arrays

Go back to Program.cs, clear the code within the Main method.

STEP 11:

Add the following code in the Main method of Program.cs.

and Ctrl + F5.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 18

The intArr is a vector of integers; and dblArr is a matrix of doubles.

intArr.Length returns the number of elements in the array.

dblArr.GetLength(0) returns the size of the first dimension (2); and dblArr.GetLength(1) returns

the size of the second dimension (3).

You can increase the number of dimensions and use GetLength in the same manner.

As well as the standard types such as int and double; you may have arrays of objects. For instance;

you can have an array of Person objects:

Person a = new Person(“a”, 20, 1.80);

Person b = new Person(“b”, 30, 1.74);

Person[] personArray = new Person[2];

personArray[0] = a;

personArray[1] = b;

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 19

5.2 Lists

Go back to Program.cs, clear the code within the Main method.

STEP 12:

Add the following code in the Main method of Program.cs.

and Ctrl + F5.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 20

Lists are like object collections. You can easily add and remove objects from the lists.

Add adds an object to the list.

Count returns the number of objects in the list.

Last returns the last element of the list.

IndexOf returns the index of an object in the list. If the returned index is -1; then the object does

not exist in the list.

Remove removes an object from the list.

RemoveAt removes the object at the given location of the list.

In terms of performance, it is better to work with arrays if the size of the array will not change

throughout the program; while lists are much easier if we are not certain about the number objects

or if we often add and remove objects.

Note that a list itself is an object. Therefore, you can have list of lists such as the two-dimensional

array:

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

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 21

5.3 Array and List Fields of a Class

Go back to Person.cs.

STEP 13:

Add the new fields and update the constructor as follows:

Now each time a Person is created;

an empty friends list,

and a double array of size 3 for the stochastic grades

will be created.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 22

STEP 14:

Add the new methods as follows:

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 23

setStochasticGrade method will get the index and grade of the exam; and assign it to the desired

element of the array.

getAverageStochasticGrade method will return the average of the three stochastic exams.

addFriend method will add a friend to the friends list.

getNbFriend will return the number of elements in the friends list.

Finally, getFriend will search the friends list by the name field. Whenever the name given in the

argument matches the name of an object in the friends list; the method returns this person. Note

that if the code finds the friend and enters the line:

return this.friends[i];

it will return the Person and quit the method. In other words, it will not continue to the for loop

and it will not reach the

return null;

line. However, if the search fails, the method will return a null object.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 24

5.4 Check the Class

Go back to Program.cs, clear the code within the Main method.

STEP 15:

Add the following code in the Main method of Program.cs.

and Ctrl + F5.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 25

Note that friends is a field of the Person class. Therefore,

both Person objects and PhdStudent objects may have friends;

Also note that friends is a collection of Person objects. Therefore,

the collection may contain Person and PhdStudent objects.

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 26

So far, we have run the program and observed the results from the console.

While debugging, it is better to use Step Into, Step Over, and Toggle Breakpoint options.

STEP 16:

Open Program.cs and press F11 to Step Into (press twice).

The highlighted line is the line to be executed next.

Press F11 again; the PhdStudent constructor will be called:

If you place the cursor on the arguments, you may see the passed values.

Continue pressing F11 until you reach the second line of the Main.cs:

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 27

STEP 17:

If you want to move on, but do not want to step into the details of the constructor method; you

can use Step Over option.

At the second line of the Main.cs press F10 to Step Over.

The code will directly go to the third line:

You can place the cursor on objects to see the details:

L1: C# CLASSES 10/13/16

Uğur Arıkan ([email protected] ; http://people.sutd.edu.sg/~ugur_arikan/) 28

STEP 18:

Now we are at the third line. Suppose that we do not want to check the code till the line that

uses the getFriend method. Go to the line using the method and press F9 to add a breakpoint

(you may remove the breakpoint again by pressing F9):

Now press F5 to run the code till the first breakpoint (or till the end if there are no breakpoints):