C# Summer course - Lecture 3

23
Introduction to C# Lecture 3 FCIS Summer training 2010, 1 st year.

description

C# summer training for FCIS, 2010. Lecture 3

Transcript of C# Summer course - Lecture 3

Page 1: C# Summer course - Lecture 3

Introduction to C#

Lecture 3

FCISSummer training 2010, 1st year.

Page 2: C# Summer course - Lecture 3

Contents

Creating new classes Accessibility modifiers (private, public &

protected) Constructors Method calls & this Static methods List boxes and combo boxes Parent and child forms Code example: contact list

Page 3: C# Summer course - Lecture 3

Class Definition

class <name>

{

<member 1>

<member 2>

...

} Members can be:

− Fields (member variables)− Methods (member functions)

Inside classes you could also define inner classes, structs, interfaces...

Page 4: C# Summer course - Lecture 3

Class Definition - Example class Unit // strategy game

{

int health, maxHealth;

int weaponDamage;

Point location;

Image img;

void Attack(Unit otherUnit) {

.......

}

void Draw(Graphics g) {

......

}

}

Page 5: C# Summer course - Lecture 3

Accessibility modifiers

public : visible to all code; inside and outside the class.

private (default) : visible only to code inside the same class

protected : visible only to code inside the class and derived classes [discussed in lecture 4].

classes themselves have accessibility modifiers [public or internal (default) ]

Page 6: C# Summer course - Lecture 3

Accessibility modifiers

How should we decide to make something public or private? If it's part of the class's interface (how external code

uses it) it should be public. If it's part of the implementation (how the class does

it's job) it should be made private. In general, favor "private" over "public"

− Allows you to change implementation without breaking existing code.

− Reduces complexity of the code that uses the class− Compatible with the principle of encapsulation.

Page 7: C# Summer course - Lecture 3

Class Definition – Example 2public class Unit // strategy game

{

int health, maxHealth;

int weaponDamage;

Point location;

Image img;

public void Attack(Unit otherUnit) {

.......

}

public void Draw(Graphics g) {

......

}

}

Still private

Page 8: C# Summer course - Lecture 3

Constructors

Constructor are called automatically when you create an object with new

They look like functions with the same name as the class and have no return value

Usually, they need to be public (but private in some situations)

A constructor can be overloaded by having multiple constructors with different parameter counts or different parameter types.

Page 9: C# Summer course - Lecture 3

Constructorsclass Point

{

int x,y;

public Point( ) { x = 0; y = 0; }

public Point(int _x, int _y ) { x = _x; y = _y;}

}

class Person {

string name, age;

public Person(string theName, string theAge) {

name = theName;

age = theAge;

}

public Person(string name) : this(name, 10)

{

}

}

Page 10: C# Summer course - Lecture 3

Method callsPoint p = new Point(0, 0);

Point p2 = new Point(30.0, 40.0);

double d = p.DistanceFrom(p2); DistanceFrom takes only one parameter?

string n = x.ToString( ); ToString( ) takes no parameters? Remember: A method is called on an object.

(Other languages say "A message is sent to an object”)

The "object on which we called the method" is the call target. Like p or x in the examples.

Page 11: C# Summer course - Lecture 3

Method calls When we call x.display( ), we are telling x to

display itself. When we call k.ToString( ) we are asking k to give itself represented as a string.

When we call p1.Distance(p2) we are asking the point p1 to give the distance between itself and p2.

Does an object understand the concept of "myself"?

...Yes, only "myself" is known as this.

Page 12: C# Summer course - Lecture 3

Method calls class Point {

double x, y;

public Point(double _x, double _y)

{

this.x = _x;

this.y =_y;

}

public double Distance(Point p2)

{

double a = this.x – p2.x;

double b = this.y – p2.y;

return Math.Sqrt(a * a + b * b);

}

}

Page 13: C# Summer course - Lecture 3

Method calls

The value of the target during method call is the same as the value of this during method execution.

Page 14: C# Summer course - Lecture 3

Static methods Some things do are not members of objects...

A function like Console.WriteLine(...) does not work on a specific object (the program assumes one console).

Functions like Sin, Cos, Sqrt could be made members of the type Double, but they would make the type too big.

A variable that records the count of Person object in the whole program does not belong to any specific person...

A function that does some calculation before creating a Point object cannot be called on a point before it is created

Page 15: C# Summer course - Lecture 3

Static methods class Point

{

double x, y;

public Point(int _x, int _y)

{

x = _x;

y = _y;

}

public static Point MakeFromR_Theta(double r,

double theta)

{

int x = r * Math.Cos(theta);

int y = r * Math.Sin(theta);

return new Point(x, y);

}

}

Page 16: C# Summer course - Lecture 3

Static methods class Test

{

static void Main()

{

Point p1 = new Point(40.0, 40.0);

Point p2 = Point.MakeFromR_Theta(100.0, 0.3);

}

}

Page 17: C# Summer course - Lecture 3

Static methods All of Methods, Variables and properties can be static

An example of static properties is Color.White It is meaningless to use this in a static method, since

there is no target for the method call. Static methods can directly call only other static

methods. To call non-static methods it has to do this via an object. Non-static methods are free to call static methods.

Similarly, static methods can access non-static variables only from an object, even in their own class.

Static methods can access private members of objects in their own classes (since they are still part of the class).

Page 18: C# Summer course - Lecture 3

The type 'object' In C# there's a special class, called 'object'

Any other type is a subtype of object.

A subtype can be assigned to a variable of it's supertype

object obj1 = new Person( ); object obj2 = 15; object obj3 = "Hello";

The opposite is not generally true, unless there's a cast involved

object obj4 = new Square( ); Square s = obj4; // WRONG!! Square s2 = (Square) obj4; // CORRECT

The cast means "perform a runtime type-check, and if it succeeds, continue".

Page 19: C# Summer course - Lecture 3

List boxes list1.Items.Add("Item 1"); // Adding

Actually you can pass any object to Add, not just strings:

list1.Items.Add(15);

list1.Items.Add(button1); object t =list1.Items[4]; // Accessing string s = list1.Items[1].ToString( ) // Converting to a string

// before usage Actually, the ListBox.Items property is a collection, so it

has Add, Remove, RemoveAt, ...etc. It also supports enumeration with foreach

You can also fill a list box's member in design-time by editing the "Items" property in the properties window

Page 20: C# Summer course - Lecture 3

List box selection The SelectedIndex property

-1 If no selection Otherwise a 0-based index of the selected item in the list.

The SelectedItem property

null if no selection Otherwise the selected item (as an object, not a string).

The SelectedIndexChanged event: called when the user changes the selection (also called if the user re-selects the same item).

Note: List boxes also have SelectedIndices and SelectedItems properties in case the user can select multiple items (can be set from the SelectionMode property).

Page 21: C# Summer course - Lecture 3

Combo boxes A combo box has a Text property like a text box and

an Items property like a list box. (This is why it's a combo box).

It also has SelectedIndex, SelectedItem, SelectedIndexChanged...etc

Since you already know text and list boxes, you can work with combo boxes.

A combo box has a property called DropDownStyle, it has 3 values:

Simple: Looks like a textbox on top of a listbox DropDown: Has a small arrow to show the listbox DropDownList: Allows you to open a list with the small

arrow button, but you can select only and not edit.

Page 22: C# Summer course - Lecture 3

Example

The contact list

Page 23: C# Summer course - Lecture 3

Next time...

Inheritance Polymorphism Dynamic binding