46
C# Programming Basics Supplemental Material

C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Embed Size (px)

Citation preview

Page 1: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

C# Programming Basics

Supplemental Material

Page 2: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions Operators Conditionals Loops

Page 3: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Control Events Most ASP.Net pages will contain

controls such as textboxes and buttons that will allow the user to interact with them.

When some action is performed, the control will raise an event (call handler code)

Page 4: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Control Events and Subroutines

When an event is raised, handler code is called.

<form runat="server"><asp:Button id="btn1" runat="server"

OnClick="btn1_Click" Text="Click Me" /><asp:Label id="lblMessage"

runat="server" /></form>

// Located in the code behind class for the formpublic void btn1_Click(Object s, EventArgs e) {

lblMessage.Text = "Hello World";}

Page 5: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

For Example:Button Control Events… OnClick – when user clicks a button OnCommand – When user clicks button OnLoad – When page first loads and button loads OnInit – When button is initialized OnPreReader- just before button is drawn OnUnload – When button is unloaded from

memory OnDisposed – when button is released from

memory OnDataBinding – When button is bound to a data

source

Page 6: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Components of a Subroutine

The access specifier defines the scope of the subroutine. public is a global subroutine that can be used anywhere. Private is available in a specific class. Most subroutines will be public.

public void btn1_Click(Object s, EventArgs e) { lblMessage.Text = "Hello World";

}

Page 7: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Components of a Subroutine

Designates the data type of the value to be returned from the subroutine. void says the block of code does not

return a value Other data types could be returned

public void btn1_Click(Object s, EventArgs e) { lblMessage.Text = "Hello World";

}

Page 8: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Control Events and Subroutines

Names the subroutine or event handler

public void btn1_Click(Object s, EventArgs e) { lblMessage.Text = "Hello World";

}

Page 9: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Control Events and Subroutines

Parameters allow information to be passed into the subroutine so it can be used or modified. Object s is the object to which this event belongs Object is the base class for every class in C# EventArgs e allows an array of information to be

passes as one parameter

public void btn1_Click(Object s, EventArgs e) { lblMessage.Text = "Hello World";

}

Page 10: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Page Events Every ASP.Net page has a page object with

events associated with it These events are fired in sequential order:

Page_Init – called when page is to be initialized Page_Load- called once browser request has

been processed Page_PreRender- called once all objects on

page have reacted to browser request Page_UnLoad- called once page is ready to be

discarded

Pag

e E

ven

t O

rder

Page 11: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Variables and Declarations Variables are data that allows the

programmer to store, modify, and retrieve data.

Variables have a name, called an identifier.

A variable declaration contains the data type and name of the variable.

A variable can also be initialized when it is declared.

String strCarType , strCarColor, =“Blue”, strCarModel;

Page 12: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Common Variable TypesC# Type Description

intWhole numbers in the range -2,147,483,648 to 2,147,483,647

DecimalUp to 28 decimal places. Used often when dealing with the cost of items.

String Any text value

CharA single character (letter, number, or

symbol)

Boolean True or False

Object Base class for all types

Page 13: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Arrays Arrays allow a group of elements of a

specific type to be stored in a contiguous block of memory

Each item in the array had an offset called an index

Derived from System.Array C# arrays are zero-based Can be multidimensional

Arrays know their length(s) and rank Bounds checking is automatic

Page 14: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Arrays Declare

Allocate

Initialize

Access and assign

String[] drinkList;

String[] drinkList = new String[4];

String[] drinkList = new String[] {“Water”, “Juice”, “Soda”, “Milk”};

drinkList[0] = drinkList[1];

Page 15: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Operators in C# C# provides a fixed set of operators, whose

meaning is defined for the predefined types Some operators can be overloaded (e.g. +) The following table summarizes the C#

operators by category Categories are in order of decreasing precedence Operators in each category have the same

precedence

Page 16: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Operators and Precedence

Category Operators

Primary

Grouping: (x)Member access: x.yMethod call: f(x)Indexing: a[x]Post-increment: x++Post-decrement: x—Constructor call: newType retrieval: typeofArithmetic check on: checkedArithmetic check off: unchecked

Page 17: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Operators and Precedence

Category Operators

Unary

Positive value of: +Negative value of: -Not: !Bitwise complement: ~Pre-increment: ++xPost-decrement: --xType cast: (T)x

MultiplicativeMultiply: *Divide: /Division remainder: %

Page 18: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Operators and Precedence

Category Operators

AdditiveAdd: +Subtract: -

ShiftShift bits left: <<Shift bits right: >>

Relational

Less than: <Greater than: >Less than or equal to: <=Greater than or equal to: >=Type equality/compatibility: isType conversion: as

Page 19: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Operators and Precedence

Category Operators

EqualityEquals: ==Not equals: !=

Bitwise AND &

Bitwise XOR ^

Bitwise OR |

Logical AND &&

Logical OR ||

Page 20: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Operators and Precedence

Category OperatorsTernary

conditional ?:

Assignment=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=

Page 21: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Statement Syntax Statements are terminated with a

semicolon (;) Just like C, C++ and Java Block statements { ... } don’t need

a semicolon

Page 22: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Expression Statements Statements must do work

Assignment, method call, ++, --, new

static void Main() { int a, b = 2, c = 3; a = b + c; a++; MyClass.Foo(a,b,c); Console.WriteLine(a + b + c); a == 2; // ERROR!}

Page 23: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Statementsif Statement

Requires a bool expression

int Test(int a, int b) { if (a > b) return 1; else if (a < b) return -1; else return 0;}

Page 24: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Statementsswitch Statement

Can branch on any predefined type (including string) or enum

Must explicitly state how to end case With break, goto case, goto label, return, throw or continue

Not needed if no code supplied after the label

Page 25: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Statementsswitch Statement

int Test(string label) { int result; switch(label) { case null: goto case “runner-up”; case “fastest”: case “winner”: result = 1; break; case “runner-up”: result = 2; break; default: result = 0; } return result;}

Page 26: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Statementswhile Statement

Requires bool expressionint i = 0;while (i < 5) { ... i++;}

int i = 0;do { ... i++;}while (i < 5);

while (true) { ...}

Page 27: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Statementsfor Statement

for (int i=0; i < 5; i++) { ...} for (;;)

{ ...}

Page 28: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Statements foreach Statement

Iteration through arrays or collections

foreach allows “read only” access to items in a collection

foreach (string s in arrayName) { lblMessage.Text=item;}

Page 29: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

StatementsJump Statements

break Exit inner-most loop

continue End iteration of inner-most

loop goto <label>

Transfer execution to label statement

return [<expression>] Exit a method

throw Used in exception handling

Page 30: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Namespaces Namespaces provide a way to

uniquely identify a type Provides logical organization of types Namespaces can span assemblies Can nest namespaces There is no relationship between

namespaces and file structure (unlike Java) The fully qualified name of a type includes

all namespaces

Page 31: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Namespaces

namespace N1 {     // N1 class C1 {   // N1.C1 class C2 {   // N1.C1.C2 }     }     namespace N2 {    // N1.N2 class C2 { // N1.N2.C2     }     } }

Page 32: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Namespaces The using statement lets you use

types without typing the fully qualified name

Can always use a fully qualified name

using N1;

C1 a; // The N1. is implicitN1.C1 b; // Fully qualified name

C2 c; // Error! C2 is undefinedN1.N2.C2 d; // One of the C2 classesC1.C2 e; // The other one

Page 33: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Namespaces The using statement also lets you

create aliases

using C2 = N1.C1.C2;using N2 = N1.N2;

C2 a; // Refers to N1.C1.C2N2.C1 b; // Refers to N1.N2.C1

Page 34: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Namespaces Best practice: Put all of your types

in a unique namespace Have a namespace for your

company, project, product, etc. Look at how the .NET Framework

classes are organized

Page 35: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Namespaces in .Net To use certain features .Net we can import

the namespace into our ASP.Net page For example, if you want to access an SQL

database from a web page you would import “System.Data.SQLClient” (more on this later)

<@ Import Namespace=“System.Data.SQLClient” %>

Page 36: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Objects, instances and classes Identity

Every instance has a unique identity, regardless of its data

Encapsulation Data and function are packaged together Information hiding An object is an abstraction

User should NOT know implementation details

Key Object-Oriented Concepts

Page 37: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Class Dog

Properties: Breed Age Color Weight Shot Record

Methods: sit() layDown() eat() run()

A Class in OOP encapsulates properties and methods

A class, like a blueprint, is used to make instances or objects

Page 38: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Creating an Instance

Property Values:

Name: Kazi Breed: Border

Collie Age: 2 years Color: Black

and White Weight: 23

Pounds

Properties: Name

Breed Age Color Weight

CreateInstance

Methods: Sit Play

Dead Eat Run

Methods: Sit Play

Dead Eat Run

Page 39: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Instantiating a Class Use the new operator to create an

object of a class Properties and methods of the

object can now be accessed

Button MyButton = new Button();

Button.Text=“ Click Me”;

Page 40: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Scope Encapsulation hides certain

properties and methods inside the class Some class members need to be

accessed from outside the class. These are made public

Those that are hidden from the outside are private

Those that can only be accessed through inheritance are protected

Page 41: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Inheritance in C# In OOP, types are arranged in a

hierarchy A Base class is the parent class A Derived class is the child class

Object is the Base class of all other types in C#

C# only allows single inheritance of classes

C# allows multiple inheritance of interfaces

Object

Animal

Dog

Page 42: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Code-Behind

Splits visual design from functional development

This allows code developers to work separately from presentational designers

Code render blocks are placed in a separate C#, .cs file

This prevents “spaghetti” code and helps make pages more understandable

Page 43: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Code-Behind Example

sample.aspx contains page layout and static content

sample.aspx inherits from the class Sample The definition of class Sample is in the

Sample.cs file<%@ Page Inherits="Sample" Src="Sample.cs" %>

<asp:Button id="btnSubmit" Text="Click Me" runat="server" onClick="Click" />

Page 44: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Code-Behind Sample Class

Because the code-behind of our page needs to use ASP.Net code, we inherit from the .Net class Page

Data members are declared protected to hide them from direct access

using System;using System.Web.UI;using System.Web.UI.WebControls;

public class Sample : System.Web.UI.Page { protected Button btnSubmit; protected Label lblMessage;

public void Click(Object s, EventArgs e) { lblMessage.Text = "Hello World"; }}

Page 45: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Code-Behind Sample Class

The Click subroutine is defined inside the class as a public method

This encapsulates the code render block inside the Sample page class

using System;using System.Web.UI;using System.Web.UI.WebControls;

public class Sample : System.Web.UI.Page { protected Button btnSubmit; protected Label lblMessage;

public void Click(Object s, EventArgs e) { lblMessage.Text = "Hello World"; }}

Page 46: C# Programming Basics Supplemental Material. C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions

Summary

C# is an Object Oriented Programming Language

It has the safety and strength of a full-fledged programming language

Variables are strongly typed Classes encapsulate properties and methods Inheritance allows reuse of code and

increases productivity The ASP.Net code-behind mechanism allows

the separation of application code from presentational elements