introduction to c# 01204111 computer and programming

74
Introduction to C# 01204111 Computer and Programming

Upload: blaine-graddick

Post on 14-Dec-2015

235 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Introduction to C# 01204111 Computer and Programming

Introduction to C#

01204111 Computer and Programming

Page 2: Introduction to C# 01204111 Computer and Programming

Agenda

• Why two languages?• Differences between Python

and C#• C# overview• Event-driven programming

Page 3: Introduction to C# 01204111 Computer and Programming

Why Two Languages?

• There exist many languages which are quite different from each other

• Python is easy for beginners, but its flexibility makes it different from other languages you will likely use

• The two languages were carefully chosen so that they have distinct syntax– So you will see and learn various

programming styles

Page 4: Introduction to C# 01204111 Computer and Programming

Our First C# Programusing System;

class Program{  public static void Main(string[] args)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }}

What does this program

do?

Page 5: Introduction to C# 01204111 Computer and Programming

Dissect The Programusing System;

class Program{  public static void Main(string[] args)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }}

The main program is contained in a

function (method) called Main

Page 6: Introduction to C# 01204111 Computer and Programming

Dissect The Programusing System;

class Program{  public static void Main(string[] args)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }}

A pair of braces { } are used to specify a block

of code

Page 7: Introduction to C# 01204111 Computer and Programming

Dissect The Method Main  public static void Main(string[] ar

gs)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }

Randomly pick a number between

1 - 100

Page 8: Introduction to C# 01204111 Computer and Programming

Dissect The Method Main  public static void Main(string[] ar

gs)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }

Repeat as long asg != answer

Page 9: Introduction to C# 01204111 Computer and Programming

Dissect The Method Main  public static void Main(string[] ar

gs)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }

Print a string, then read an integer and

store it in the variable g

Page 10: Introduction to C# 01204111 Computer and Programming

Dissect The Method Main  public static void Main(string[] ar

gs)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }

Compare g and answer, then

display the hint

Page 11: Introduction to C# 01204111 Computer and Programming

Dissect The Method Main  public static void Main(string[] ar

gs)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }

Tell the user that the answer is

correct

Page 12: Introduction to C# 01204111 Computer and Programming

Dissect The Program: Outer

Blockusing System;

class Program{  public static void Main(string[] args)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }}

Indicate that this program will use functions from

standard library

Page 13: Introduction to C# 01204111 Computer and Programming

Dissect The Programusing System;

class Program{  public static void Main(string[] args)  {    Random r = new Random();    int answer = 1 + (r.Next() % 100);    int g;

    do {      Console.Write("Guess a number: ");      g = int.Parse(Console.ReadLine());      if(g > answer)        Console.WriteLine("Too large");      else if(g < answer)        Console.WriteLine("Too small");    } while(g != answer);

    Console.WriteLine("That's correct");  }}

Every method must reside in a

class

Page 14: Introduction to C# 01204111 Computer and Programming

Coding in Different Languages

Hello,May I have a

fried rice, and water please?

Bonjour, Puis-je avoir un riz frit, et de l'eau s'il vous plaît?

Solving the same task using a different language usually has on the same flow of thought and steps. The only differences are syntax and wording.

Page 15: Introduction to C# 01204111 Computer and Programming

C# Program Structure

using System;

namespace Sample{ class Program { static void Main() { Console.WriteLine("Hello, world"); } }}

C# uses braces { } to specify scopes of things

Program on the left contains1.namespace Sample2.class Program3.method Main

Page 16: Introduction to C# 01204111 Computer and Programming

C# Program Structure

using System;

namespace Sample{ class Program { static void Main() { Console.WriteLine("Hello, world"); } }}

C# statements are contained in a bigger structure

Statements are inside a method

Methods are inside a class

Classes may or may not be inside a namespace

Page 17: Introduction to C# 01204111 Computer and Programming

The Universe of C# Programs

Namespace System

Class ConsoleWriteLine

ReadLine

Write

Class Integer

Parse

ToString

Class RandomNext

Class Float

Namespace Sample

(Our own namespace)

ClassProgram

Main

Class X

Class Y …

Page 18: Introduction to C# 01204111 Computer and Programming

• The statement using System; at the beginning of the program indicates that our program will use the System namespace as our own namespace

using System

Namespace Sample

(Our own namespace)

ClassProgram

Main

Namespace System

Class ConsoleWriteLine

ReadLine

Write

Class Integer

Parse

ToString

Class RandomNext

Class Float

using System;

namespace Sample{ class Program { …… }}

Page 19: Introduction to C# 01204111 Computer and Programming

The Main Program: Method Main

using System;

namespace Sample{ class Program { static void Main() {

} }}

The program always starts at the method Main

We will write our main program here.

Page 20: Introduction to C# 01204111 Computer and Programming

Just Ignore Them (For Now)

• What are classes?• What is this "static void"

thing?We will not answer these questions at the moment. For the time being, just use them

as shown. You will know when the time comes…

We will not answer these questions at the moment. For the time being, just use them

as shown. You will know when the time comes…

Page 21: Introduction to C# 01204111 Computer and Programming

Example: Distance Calculation

• A still object starts moving in a straight line with the acceleration of a m/s2 for t seconds.

• How far is it from its starting point?

Page 22: Introduction to C# 01204111 Computer and Programming

Developing C# Programs

• We will use a tool called Integrated Development Environment, or IDE–Allows code editing, testing, and debugging

–Similar to WingIDE

• We will first start with text-only programs–Also known as console applications

Page 23: Introduction to C# 01204111 Computer and Programming

Start Writing Program

• The IDE we will be using is call SharpDevelop.• Microsoft Visual Studio Express can also be used.

Page 24: Introduction to C# 01204111 Computer and Programming

Create a Solution • A program is called

a solution• Choose New

Solution– Choose Console

Application– Enter solution name

• Once done, stub code will be created

Page 25: Introduction to C# 01204111 Computer and Programming

IDE Window• Code editor is

located at the center of the window

• Other parts show properties and structure of the program

Page 26: Introduction to C# 01204111 Computer and Programming

using System;

namespace mecha1{  class Program  {    public static void Main(string[] args)    {      double a, t, s;            Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());      Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());            s = a*t*t/2.0;            Console.WriteLine("Distance = {0}", s);    }  }}

First Program

Identify similarities and

differences, compared to a

Python program

Page 27: Introduction to C# 01204111 Computer and Programming

using System;

namespace mecha1{  class Program  {    public static void Main(string[] args)    {      double a, t, s;            Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());      Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());            s = a*t*t/2.0;            Console.WriteLine("Distance = {0}", s);    }  }}

First Program

Every statement ends with a ; (semi-colon)

Page 28: Introduction to C# 01204111 Computer and Programming

using System;

namespace mecha1{  class Program  {    public static void Main(string[] args)    {      double a, t, s;            Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());      Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());            s = a*t*t/2.0;            Console.WriteLine("Distance = {0}", s);    }  }}

First Program

Variables must be declared with

proper data types before used.

Here, double is a data type for storing a real

number.

Page 29: Introduction to C# 01204111 Computer and Programming

using System;

namespace mecha1{  class Program  {    public static void Main(string[] args)    {      double a, t, s;            Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());      Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());            s = a*t*t/2.0;            Console.WriteLine("Distance = {0}", s);    }  }}

First Program

Calculate the result and store it

in s

Page 30: Introduction to C# 01204111 Computer and Programming

using System;

namespace mecha1{  class Program  {    public static void Main(string[] args)    {      double a, t, s;            Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());      Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());            s = a*t*t/2.0;            Console.WriteLine("Distance = {0}", s);    }  }}

First Program

Output Statements

Page 31: Introduction to C# 01204111 Computer and Programming

using System;

namespace mecha1{  class Program  {    public static void Main(string[] args)    {      double a, t, s;            Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());      Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());            s = a*t*t/2.0;            Console.WriteLine("Distance = {0}", s);    }  }}

First Program

Input Statement reads user input as

a string

Page 32: Introduction to C# 01204111 Computer and Programming

using System;

namespace mecha1{  class Program  {    public static void Main(string[] args)    {      double a, t, s;            Console.Write("Enter a: ");      a = double.Parse(Console.ReadLine());      Console.Write("Enter t: ");      t = double.Parse(Console.ReadLine());            s = a*t*t/2.0;            Console.WriteLine("Distance = {0}", s);    }  }}

First Program

Convert string into real number

(double)

Page 33: Introduction to C# 01204111 Computer and Programming

Difference: Use { } To Indicate Blocks

//// Other parts are omitted//static void Main(){ int n = int.Parse(Console.ReadLine()); int i = 1; while(i <= n) { if(i % 3 == 0) { Console.WriteLine(i); } } }

def main(): n = int(input()) i = 1 while i <= n: if i % 3 == 0: print(i)

Python C#

Python uses indentation

C# uses { }

Page 34: Introduction to C# 01204111 Computer and Programming

Difference: Use { } To Indicate Blocks

//// Other parts are omitted//static void Main(){ int n = int.Parse(Console.ReadLine()); int i = 1; while(i <= n) { if(i % 3 == 0) { Console.WriteLine(i); } } }

C#//// Other parts are omitted//static void Main(){int n = int.Parse(Console.ReadLine());int i = 1;while(i <= n) {if(i % 3 == 0){Console.WriteLine(i); }} }

C#

Indentations have no effect on program logic. They are used for improving readability.

Page 35: Introduction to C# 01204111 Computer and Programming

Difference: Use { } To Indicate Blocks

//// Other parts are omitted//static void Main(){ int n = int.Parse(Console.ReadLine()); int i = 1; while(i <= n) { if(i % 3 == 0) { Console.WriteLine(i); } } }

C#//// Other parts are omitted//static void Main(){ int n = int.Parse(Console.ReadLine()); int i = 1; while(i <= n) if(i % 3 == 0) Console.WriteLine(i); }

C#

For control statements such as while or if, omitting { } means the following block contains only one statement.

Page 36: Introduction to C# 01204111 Computer and Programming

Difference: Variable Declaration

//// Other parts are omitted//static void Main(){ int n = int.Parse(Console.ReadLine()); int total = 0; int i = 0; int x; while(i < n) { x = int.Parse(Console.ReadLine()); total += x; i += 1; } }

n = int(input())total = 0i = 0while i < n: x = int(input()) total += x i += 1print(total)

Python C#

Page 37: Introduction to C# 01204111 Computer and Programming

Declaring Variables• Syntax:

<Data type> <Variable name>;<Data type> <Var name>, <Var name>, …;

• Ex:

• Initial values can be given right awayEx:

double area;int radius, counter;bool isOkay;

double area;int radius, counter;bool isOkay;

int k = 200;bool done = false;int k = 200;bool done = false;

Multiple vars.

Single var

Page 38: Introduction to C# 01204111 Computer and Programming

Basic Data Types in C#

Type Size Description Rangebool 1 byte Store truth value true / false char 1 byte Store one character character code 0 – 255byte 1 byte Store positive integer 0 – 255short 2 byte Store integer -32,768 -- 32,767int 4 byte Store integer -2.1 x 109 -- 2.1 x 109 long 8 byte Store integer -9.2 x 1018 -- 9.2 x 1018

double 16 byte Store real number ± 5.0x10-324 -- ± 1.7x10308

string N/A Store sequence of characters

N/A

Page 39: Introduction to C# 01204111 Computer and Programming

Computing Summation

• Write a program that takes a list of positive integers from user until -1 is entered, then displays the sum of all the numbers in the list

Page 40: Introduction to C# 01204111 Computer and Programming

Summation: Pythontotal = 0num = 0while num != -1: num = int(input()) if num != -1: total += numprint(total)

total = 0num = 0while num != -1: num = int(input()) if num != -1: total += numprint(total)

Page 41: Introduction to C# 01204111 Computer and Programming

Summation: C#

• Summation program written in C#static void Main()

{ int total = 0; int num = 0; while(num != -1) { num = int.Parse(Console.ReadLine()); if(num != -1) total += num; } Console.WriteLine(total);}

static void Main(){ int total = 0; int num = 0; while(num != -1) { num = int.Parse(Console.ReadLine()); if(num != -1) total += num; } Console.WriteLine(total);}

total = 0num = 0while num != -1:

num = int(input()) if num != -1: total += num

print(total)

total = 0num = 0while num != -1:

num = int(input()) if num != -1: total += num

print(total)

Page 42: Introduction to C# 01204111 Computer and Programming

C# and Python: Difference Summary• Use { } to indicate

blocks• Variables

– Must always be declared with data type specified

– One variable can store one data type

• Usually run faster

• Use indentation for blocks

• Variables– Can be used instantly

– Each variable can store any data type, which can be changed during the program execution

• Usually run slower

C# Python

Page 43: Introduction to C# 01204111 Computer and Programming

Cost and Benefit

• We lose many flexibilities in C#, but more errors can be found much earlier

Page 44: Introduction to C# 01204111 Computer and Programming

Erroneous Python Program

x = int(input("Enter price: "))if x <= 10: print("You have to pay",x,"baht.")else: print("You have to pay",y*0.95,"baht.")

Do you spot the error?Do you spot the error?Enter price: 7You have to pay 7 baht.Enter price: 7You have to pay 7 baht.

Enter price: 20Traceback (most recent call last): File "<string>", line 5, in <fragment>builtins.NameError: name 'y' is not defined

Enter price: 20Traceback (most recent call last): File "<string>", line 5, in <fragment>builtins.NameError: name 'y' is not defined

We will know only when the erroneous line gets

executed

We will know only when the erroneous line gets

executed

Page 45: Introduction to C# 01204111 Computer and Programming

Erroneous C# Program

    public static void Main(string[] args)    {      double x;      Console.Write("Enter price: ");      x = double.Parse(Console.ReadLine());

      if(x <= 10)        Console.WriteLine("You have to pay {0} baht.", x);      else        Console.WriteLine("You have to pay {0} baht.", y*0.95);            }

Do you spot the error?Do you spot the error?

This C# program will not compile. The compiler will reportThe name 'y' does not exist in the current context.

Page 46: Introduction to C# 01204111 Computer and Programming

Erroneous Python Program

x = input("Enter price: ")if x <= 10: print("You have to pay",x,"baht.")else: print("You have to pay",x*0.95,"baht.")

Do you spot the error?Do you spot the error?

There is a problem because we try to compare an integer with a stringThere is a problem because we try to compare an integer with a string

Traceback (most recent call last): File "<string>", line 2, in <fragment>builtins.TypeError: unorderable types: str() <= int()

Traceback (most recent call last): File "<string>", line 2, in <fragment>builtins.TypeError: unorderable types: str() <= int()

We will know only when the erroneous line gets

executed

We will know only when the erroneous line gets

executed

Page 47: Introduction to C# 01204111 Computer and Programming

Erroneous C# Program

    public static void Main(string[] args)    {      String x;      Console.Write("Enter price: ");      x = Console.ReadLine();

      if(x <= 10)        Console.WriteLine("You have to pay {0} baht.", x);      else        Console.WriteLine("You have to pay {0} baht.", x*0.95);            }

Do you spot the error?Do you spot the error?

This C# program won't compile. Two errors will be reported1. Operator '<=' cannot be applied to operands of

type 'string' and 'int'.2. Operator '*' cannot be applied to operands of

type 'string' and 'double'

Page 48: Introduction to C# 01204111 Computer and Programming

Choosing a Language

StrictUnintentional errors

caught before the program starts

Longer programs cause more difficulties

More limitations

StrictUnintentional errors

caught before the program starts

Longer programs cause more difficulties

More limitations

GenerousEasy and faster to

write program, with more flexibility

Errors might be found after the program

startedCan be a problem with

large programs

GenerousEasy and faster to

write program, with more flexibility

Errors might be found after the program

startedCan be a problem with

large programs

Page 49: Introduction to C# 01204111 Computer and Programming

Justification of This Course

• This course begins with Python, which is easy for beginners

• The second half uses C#, which has more restrictions, so we write more organized programs

• This is to allow students to understand the programming concept, without being tied to a specific language

Page 50: Introduction to C# 01204111 Computer and Programming

Your Choices• There are many

other programming languages

• Most importantly, pick the right tool for the right job

Page 51: Introduction to C# 01204111 Computer and Programming

Executing a Program: Review

• We write a program in a high-level language

• But the CPU understands only machine language

• There must be a process of translating what we wrote into something the CPU understands

Page 52: Introduction to C# 01204111 Computer and Programming

Executing a C# Program

• C# programs are compiled by a compiler into a form that can be executed by the computer

• However, certain software infrastructure must also be installed in the computer

C# Program C# Compiler Executable Code

Page 53: Introduction to C# 01204111 Computer and Programming

Graphic User Interface

• C# development environment provides great convenience for creating applications (programs) that interact with users graphically

• Such applications are said to contain GUI (graphics user interface); they are called GUI applications

• Let's build a simple GUI application

Page 54: Introduction to C# 01204111 Computer and Programming

Typical GUI Applications

• Users can interact with the program in many different ways

• Therefore, the sequence of execution is not certain, compared to console applications

Click hereClick hereClick here

Click here

Click here

Edit here

Edit here

Page 55: Introduction to C# 01204111 Computer and Programming

Writing a GUI Program (1)

• Consider a program that reads a set of data

• In a GUI program, user may enter values in many different orders

• Coding in sequential style is therefore not suitable in GUI programs

int w = int.Parse(Console.ReadLine());int h = int.Parse(Console.ReadLine());Console.Write("Choose unit: ");string u = Console.ReadLine();Console.Write("Choose background:");string b = Console.ReadLine();

int w = int.Parse(Console.ReadLine());int h = int.Parse(Console.ReadLine());Console.Write("Choose unit: ");string u = Console.ReadLine();Console.Write("Choose background:");string b = Console.ReadLine();

Page 56: Introduction to C# 01204111 Computer and Programming

Writing a GUI Program (2)

• As there are various ways user can interact with the program, a piece of code is written to handle each particular event–This is called event-driven

programmingWhat to do when this

button is clicked?

What to do when this button is clicked?

What to do when this button is clicked?

What to do when this value changes?

What to do when this value changes?

Page 57: Introduction to C# 01204111 Computer and Programming

Event-Driven Programming

• We will write a program that responds to an event

• When an event of interest occurs, the corresponding part of program will be executed

• Consider the following programIf this button is clicked" Change the text above to "Sawaddee"

If this button is clicked" Change the text above to "Sawaddee"

The program responds to the button click as follows:

Page 58: Introduction to C# 01204111 Computer and Programming

Create a Solution

• Choose New solution

• Choose Windows Application

• Enter the solution's name

Page 59: Introduction to C# 01204111 Computer and Programming

User Interface Design

• Once we create a Windows application–We will be able to click on the Design tab to design our window layout for the user interface

Click "Design"

Click "Tools"

Page 60: Introduction to C# 01204111 Computer and Programming

Hello, worldButtons and labels, available in the Tools tab, can be placed on the window. There properties can also be modified via the Properties box.

Buttons and labels, available in the Tools tab, can be placed on the window. There properties can also be modified via the Properties box.

Caution: do not double-click. If you do and the code window shows up, click Design to go back to the design screen.

Caution: do not double-click. If you do and the code window shows up, click Design to go back to the design screen.

Page 61: Introduction to C# 01204111 Computer and Programming

Objects on the Window

• We have already placed two objects• The IDE sets default names to the

objects as follows:

• These names can be changed, but we will stick to them for now

label1

button1

Page 62: Introduction to C# 01204111 Computer and Programming

Objects and Their Properties

• Each object on the window has editable properties.

• E.g., the button1 object has some properties shown in the right

Page 63: Introduction to C# 01204111 Computer and Programming

Properties• The Properties tab allows us to

adjust text, text font, color, etc.

Change the font by editing Font propertyChange the text by editing the Text

property

Page 64: Introduction to C# 01204111 Computer and Programming

Writing the Program• We will write the program so that

the text "Hello, world" is displayed at label1 when the button button1 is clicked–In the design window, double click button1

–The design window will disappear. The IDE will display code that allows you to edit

Page 65: Introduction to C# 01204111 Computer and Programming

Writing the Program

We will write our program in this Button1Click method

Page 66: Introduction to C# 01204111 Computer and Programming

Handling the Event

• We write an event-handling method as follows:void Button1Click(object sender, EventArgs e)

{  label1.Text = "Sawaddee";}

void Button1Click(object sender, EventArgs e){  label1.Text = "Sawaddee";}

Change the text on label1 to "Sawaddee"

ClickClick

CallsButton1Click

CallsButton1Click

Page 67: Introduction to C# 01204111 Computer and Programming

Binding Event to Method

• We can bind any method to the Click event from the Properties box

• However, by double clicking an object, the IDE will automatically create a new method to handle the object's default event.

Page 68: Introduction to C# 01204111 Computer and Programming

Adding Numbers

• Let us write a program that takes two integers, then displays their sum

• We start with the user interface design, which consists of a button, two text boxes, and a label

Page 69: Introduction to C# 01204111 Computer and Programming

User Interface Design

• New Solution, choose Windows Application

• Place objects on the design window as shown label

button

text box

text box

Page 70: Introduction to C# 01204111 Computer and Programming

Object Names

• IDE will automatically assign names for referring to those objects as shown

label1

button1

textBox1

textBox2

Page 71: Introduction to C# 01204111 Computer and Programming

Choose Better Names

• The default names do not make a lot of sense. That will make our program difficult to read

• So we replace them with better ones

resultLabel

addButton

xTextBox

yTextBox

Watch out the lower/upper casesWatch out the lower/upper cases

Page 72: Introduction to C# 01204111 Computer and Programming

Changing Names

Change the name by editing the Name property.

These names are used to refer to the objects and their properties in

our program.

Page 73: Introduction to C# 01204111 Computer and Programming

Handling Button Click

• In the design window, double click the button, then enter the following methodvoid AddButtonClick(object sender, EventArgs e)

{ int x = int.Parse(xTextBox.Text);  int y = int.Parse(yTextBox.Text);  int result = x + y;  resultLabel.Text = result.ToString();}

void AddButtonClick(object sender, EventArgs e){ int x = int.Parse(xTextBox.Text);  int y = int.Parse(yTextBox.Text);  int result = x + y;  resultLabel.Text = result.ToString();}

Page 74: Introduction to C# 01204111 Computer and Programming

Thinking Corner

• Add another button to multiply the two numbers