Post on 31-Dec-2015
C# Programming Basics
Supplemental Material
C# Programming Basics Control Events and Handlers Page Events Variables and Declarations Arrays Functions Operators Conditionals Loops
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)
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";}
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
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";
}
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";
}
Control Events and Subroutines
Names the subroutine or event handler
public void btn1_Click(Object s, EventArgs e) { lblMessage.Text = "Hello World";
}
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 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
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;
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
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
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];
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
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
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: %
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
Operators and Precedence
Category Operators
EqualityEquals: ==Not equals: !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Logical AND &&
Logical OR ||
Operators and Precedence
Category OperatorsTernary
conditional ?:
Assignment=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
Statement Syntax Statements are terminated with a
semicolon (;) Just like C, C++ and Java Block statements { ... } don’t need
a semicolon
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!}
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;}
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
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;}
Statementswhile Statement
Requires bool expressionint i = 0;while (i < 5) { ... i++;}
int i = 0;do { ... i++;}while (i < 5);
while (true) { ...}
Statementsfor Statement
for (int i=0; i < 5; i++) { ...} for (;;)
{ ...}
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;}
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
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
Namespaces
namespace N1 { // N1 class C1 { // N1.C1 class C2 { // N1.C1.C2 } } namespace N2 { // N1.N2 class C2 { // N1.N2.C2 } } }
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
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
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
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” %>
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
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
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
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”;
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
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
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
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" />
…
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"; }}
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"; }}
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