c# summer course - lecture 2

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

Upload: mohamedsamyali

Post on 01-Nov-2014

881 views

Category:

Technology


1 download

DESCRIPTION

C# summer training for FCIS, 2010. Lecture 2

TRANSCRIPT

Page 1: C# Summer course - Lecture 2

Introduction to C#

Lecture 2

FCISSummer training 2010, 1st year.

Page 2: C# Summer course - Lecture 2

Contents

References and reference types. Arrays in C# The List<T> generic collection. foreach Graphics and OnPaint( ) KeyDown, KeyUp and KeyPress Example: Controlling a picture w/ the keyboard

Page 3: C# Summer course - Lecture 2

References In C#, classes are an example of reference

types. Variables whose type is a reference type follow

reference semantics: The variables stores a reference to the object, not the object itself.

Values who have a reference type and are not initialized have the value of null

In the assignment:

x = y

x does not take a copy of the object y refers to, but takes a copy of the reference.

Let's see this with the debugger...

Page 4: C# Summer course - Lecture 2

References - quiz class Person {

public string name;

}

class Test {

static void Main() {

Person p1, p2, p3;

p1 = new Person( );

p1.Name = "Ramy";

p2 = p1;

p3 = p2;

p2 = new Person( );

p2.Name = "Saif";

p3.Name = "Samar";

}

}

What's the final value of p1.name, p2.name and p3.name ?

Page 5: C# Summer course - Lecture 2

Value types Consider the following code:

Person x, y;

x = new Person( );

x.Name = “samy”;

y = x;

y.Name = "Maher";

Now what will be the value of x.Name? If Person is a class, then x and y will be references to

the same object, and x.Name will become "Maher" If Person is a struct, y=x will make a copy of x and

assign it to y, so y will be a different object. In this case, x.Name will remain "Samy" and y.Name

will be "Maher"

Page 6: C# Summer course - Lecture 2

Value types This means that structs in C# are very different from

classes, while in C++ structs and classes are almost the same.

The C# basic data types (int, float...) are value types (in fact, they are considered structs by the language).

Many types in the .net libraries are value types, Like System.Drawing.Point and System.Drawing.Rectangle

The C# type system can convert value-typed objects into references by boxing and convert references into value-type objects by unboxing. But this is beyond the scope of this course...

Page 7: C# Summer course - Lecture 2

Arrays C# arrays declare the full type before the array name

C++: int x[10];

C#: int[ ] x;

Since arrays are reference types; their value is null until initialized:

int[ ] x; // x is null

x = new int[10]; // x is now an array object

If we declare an array of reference types (e.g an array of buttons) then all elements are null until initialized:

Button[ ] arr = new Button[10];

for(int i=0; i<10; i++) {

arr[i] = new Button( );

}

C# has array literals:

int[] arr = {1, 2, 3, 4, 5};

Person[] team = new Person[] { new Person(“Ahmed”); new Person(“Omar”), new Person(“Kamal”); };

Page 8: C# Summer course - Lecture 2

Generics and List<T> The List<T> class works like an array, but auto-expands when you add more

elements to it.

This is a generic class: To make instances of this class, you must specialize it by replacing the parameter T with a real type. For example:

List<int> myList;

myList = new List<int>;

List<Person> people = new List<Person>( );

Some useful methods and properties in List<T>:

void Add(T value)

bool Remove(T value) , void RemoveAt(int index)

void Clear( ), int IndexOf(T value)

The Count property

List<T> can be indexed with the [ ] operator like and array

List<T> has brothers and sisters in the .net libraries, like Stack<T>, Queue<T> and Dictionary<T1, T2>

Most of them live in the System.Collections.Generic namespace

Page 9: C# Summer course - Lecture 2

Foreach Foreach is used to iterate over data in a collection

Syntax:

foreach(<Type> <var> in <collection>)

{

<code>

}

Example:

int[ ] arr = {1, 2, 3, 4}

foreach(int x in arr)

{

Console.WriteLine(x);

}

Page 10: C# Summer course - Lecture 2

Foreach Foreach does not work only on arrays, it works on

many, many collection classes: It works on List<T> It works on combo box and list box items It works on all of .net's data structures It works in many other places...

When creating your own data structures, you can make them support foreach

Page 11: C# Summer course - Lecture 2

The System.Drawing.Graphics class Graphics is a class that represents something with

drawing capabilities (screen, window, printer....) Some useful methods in this class: g.DrawLine(Pen p, Point pt1, Point pt2); g.DrawLine(Pen p, int x1, int y1, int x2, int y2); g.DrawRectangle(Pen p, Rectangle r); g.DrawRectangle(Pen p, int x, int y, int width,

int height); g.DrawEllipse(Pen p, Rectangle r); g.DrawEllipse(Pen p, int x, int y, int width,

int height);

Page 12: C# Summer course - Lecture 2

Pen? A pen is an object used by Graphics to draw lines (like

a real pen). How to obtain a pen?

Use the ready-made pens like Pens.Black or Pens.Brown

Use one of the constructors for the class System.Drawing.Pen:

− Pen p = new Pen(Colors.White, 12); // Color and //width

− Pen p = new Pen(Color.FromArgb(234, 12, 124), 13); // Color and width also, color defined

// by RGB values, each from 0 to 255

Page 13: C# Summer course - Lecture 2

More Graphics functions... g.FillRectangle(Brush b, Rectange r) g.FillRectangle(Brush b, int x, int y, int w, int h) g.FillEllipse(Brush b, Rectange r) g.FillEllipse(Brush b, int x, int y, int w, int h) To obtain a brush:

Use a ready-made brush like Brushes.Blue or Brushes.White

Use one of the classes that implement a brush interface:

− Brush b = new SolidBrush(Color.Yellow);− Brush b2 = new LinearGradientBrush(

new Point(0, 10),new Point(200, 10),

Color.Red,Color.Blue);

Page 14: C# Summer course - Lecture 2

The graphics class is rich... Drawing images:

Bitmap b = Bitmap.FromFile("...."); g.DrawImage(b, 20, 30);

The Graphics class has many more drawing functions. And even the functions we explained, like DrawLine( ),

have many more varieties.

Page 15: C# Summer course - Lecture 2

The paint event Some actions can invalidate the drawing on a form:

Minimizing and then maximizing the window. Moving another program in front of the window then

moving it away. Resizing the window. …

When this happens, the form call the paint event to redraw the window contents.

Page 16: C# Summer course - Lecture 2

The paint event private void Form1_Paint(object sender, PaintEventArgs e)

{

}

An object of type PaintEventArgs is given to you in the paint event, it contains two important properties: ClipRectange : the rectangle in which to paint. Graphics : A graphics on which to draw the window

contents. You should use the provided graphics object to draw.

You don't need to use the ClipRectangle but it could lead to faster drawing.

Page 17: C# Summer course - Lecture 2

Obtaining a Graphics without Paint I want to draw on the form, but not in the paint event How do I get a graphics? Ask the form to get one for you:

void button1_Click(object sender, EventArgs e)

{

Graphics g = this.CreateGraphics();

g.DrawLine(Pens.Black, 0, 0, 100, 100);

g.Dispose( );

} You should not dispose the graphics in the

PaintEventArgs, but you need to dispose it if you got it from CreateGraphics()

Page 18: C# Summer course - Lecture 2

KeyDown and KeyUp The KeyDown event is called when the user pushes a

key on the keyboard. The KeyUp event is called when the user releases the

key. The event, like paint( ), has a parameter with additional

information. It's type is KeyEventArgs. KeyEventArgs has many useful properties, including:

Boolean properties called "Alt", "Control" and "Shift" to tell if those keys were pressed during the event.

A "KeyCode" property. Its type is the enumeration Keys

− In C#, enum values are in the form enumName.valueName

Page 19: C# Summer course - Lecture 2

KeyDown and KeyUpprivate void Form1_KeyDown(object sender,

KeyEventArgs e)

{

if (e.KeyCode == Keys.Down)

{

text1.Text = "The down arrow was pressed";

}

if (e.Alt == true && e.KeyCode == Keys.Back)

{

text1.Text = "You pressed alt+backspace";

}

}

Page 20: C# Summer course - Lecture 2

KeyPress The KeyPress event is called when a character is

generated by the keyboard. It has a KeyPressEventArgs parameter, this

parameter has a property called KeyChar Some differences from KeyDown/KeyUp:

KeyPress can generate several events if the key is held for a while.

KeyPress can generate only printable characters (e.g the page up key has KeyDown/KeyUp but no KeyPress).

The KeyChar parameter is of type char and not KeyCode. The KeyChar differs by keyboard state (e.g it can be a capital or small letter, or an Arabic letter...)

Page 21: C# Summer course - Lecture 2

Remarks from MSDN Key events occur in the following order:

1. KeyDown

2. KeyPress

3. KeyUp The KeyChar property is read/write. It can be used to

modify the keypress event data. To make the form handle keyboard events before its

controls, set the form's KeyPreview property to true. After that, the system will also send the event to the

control, unless you set e.Handled property in your form's event-handling method to true.

Page 22: C# Summer course - Lecture 2

Sample program The "MoveImageWithKeyboard" sample.

Page 23: C# Summer course - Lecture 2

Next time...

Creating your own classes.