Overview
Introduction tothe .NET Platform
Overview of the .NET Framework
Benefits of the .NET Framework
The .NET Framework Components
Languages in the .NET Framework
3.
Introduction to the.NET Platform
The .NET Framework
.NET My Services
The .NET Enterprise Servers
Visual Studio .NET
4.
Overview of the.NET Framework
Win32
Win32
Message
Message
Queuing
Queuing
COM+
COM+
(Transactions, Partitions,
(Transactions, Partitions,
Object Pooling)
Object Pooling)
IIS
IIS WMI
WMI
Common Language Runtime
Common Language Runtime
.NET Framework Class Library
.NET Framework Class Library
ADO.NET: Data and XML
ADO.NET: Data and XML
XML Web Services
XML Web Services User Interface
User Interface
Visual
Basic
C++ C#
ASP.NET
ASP.NET
Perl J# …
5.
Benefits of the.NET Framework
Based on Web standards and practices
Designed using unified application models
Easy for developers to use
Extensible classes
Windows API
Windows API
Visual Basic Forms
Visual Basic Forms MFC/ATL
MFC/ATL ASP
ASP
.NET Framework
.NET Framework
6.
The .NETFramework Components
Common Language Runtime
.NET Framework Class Library
ADO.NET: Data and XML
Web Forms and XML Web Services
User Interface for Windows
7.
Common Language Runtime
BaseClass Library Support
Base Class Library Support
Thread Support
Thread Support COM Marshaler
COM Marshaler
Type Checker
Type Checker Exception Manager
Exception Manager
MSIL to Native
MSIL to Native
Compilers
Compilers
Code
Code
Manager
Manager
Garbage
Garbage
Collector
Collector
Security Engine
Security Engine Debug Engine
Debug Engine
Class Loader
Class Loader
ADO.NET: Data andXML
ADO.NET: Data and XML
ADO.NET: Data and XML
DataSet
DataSet DataRow
DataRow
DataTable
DataTable DataView
DataView
System.Data
System.Xml.Schema
System.Xml.Schema
System.Xml.Serialization
System.Xml.Serialization
System.Xml
10.
ASP.NET
ASP.NET
Web Forms andXML Web Services
System.Web
System.Web
Configuration
Configuration SessionState
SessionState
Caching
Caching Security
Security
Services
Services
Description
Discovery
Protocols
UI
UI
HtmlControls
WebControls
11.
User Interface forWindows
System.Drawing
System.Drawing
System.Windows.Forms
System.Windows.Forms
12.
Languages in the.NET Framework
C# – Designed for .NET
New component-oriented language
Managed Extensions to C++
Enhanced to provide more power and control
Visual Basic .NET
New version of Visual Basic with substantial language innovations
JScript .NET
New version of JScript that provides improved performance and productivity
J# .NET
.NET Java-language support enabling new development and Java migration
Third-party Languages
13.
Review
Introduction tothe .NET Platform
Overview of the .NET Framework
Benefits of the .NET Framework
The .NET Framework Components
Languages in the .NET Framework
Overview
Structure ofa C# Program
Basic Input/Output Operations
Recommended Practices
Compiling, Running, and Debugging
16.
Structure ofa C# Program
Hello, World
The Class
The Main Method
The using Directive and the System Namespace
Demonstration: Using Visual Studio to Create
a C# Program
The Class
AC# application is a collection of classes, structures,
and types
A class Is a set of data and methods
Syntax
A C# application can consist of many files
A class cannot span multiple files
class name
{
...
}
19.
The Main Method
When writing Main, you should:
Use an uppercase “M”, as in “Main”
Designate one Main as the entry point to the program
Declare Main as public static void Main
Multiple classes can have a Main
When Main finishes, or returns, the application quits
20.
The using Directiveand the System Namespace
The .NET Framework provides many utility classes
Organized into namespaces
System is the most commonly used namespace
Refer to classes by their namespace
The using directive
System.Console.WriteLine("Hello, World");
using System;
…
Console.WriteLine("Hello, World");
Basic Input/OutputOperations
The Console Class
Write and WriteLine Methods
Read and ReadLine Methods
23.
The Console Class
Provides access to the standard input, standard output,
and standard error streams
Only meaningful for console applications
Standard input – keyboard
Standard output – screen
Standard error – screen
All streams may be redirected
24.
Write and WriteLineMethods
Console.Write and Console.WriteLine display
information on the console screen
WriteLine outputs a line feed/carriage return
Both methods are overloaded
25.
Read and ReadLineMethods
Console.Read and Console.ReadLine read user input
Read reads the next character
ReadLine reads the entire input line
26.
Commenting Applications
Commentsare important
A well-commented application permits a developer to
fully understand the structure of the application
Single-line comments
Multiple-line comments
/* Find the higher root of the
quadratic equation */
x = (…);
// Get the user’s name
Console.WriteLine("What is your name? ");
name = Console.ReadLine( );
Overview
Common TypeSystem
Naming Variables
Using Built-in Data Types
Creating User-Defined Data Types
Converting Data Types
30.
Common TypeSystem
Overview of CTS
Comparing Value and Reference Types
Comparing Built-in and User-Defined Value Types
Simple Types
31.
Overview of CTS
CTS supports both value and reference types
Reference Type
Type
Value Type
32.
Comparing Value andReference Types
Value types:
Directly contain their
data
Each has its own
copy of data
Operations on one
cannot affect another
Reference types:
Store references to their
data (known as objects)
Two reference variables
can reference same object
Operations on one can
affect another
33.
Comparing Built-in andUser-Defined Value Types
Examples of
built-in value types:
int
float
Examples of user-defined
value types:
enum
struct
User-Defined
Value Types
Built-in Type
Simple Types
Reserved keywordsAlias for struct type
sbyte
System.SByte
byte
System.Byte
short
System.Int16
ushort
System.UInt16
int
System.Int32
Uint
System.UInt32
long
System.Int64
ulong
System.UInt64
char
System.Char
36.
Rules and Recommendationsfor Naming Variables
Rules
Use letters, the underscore,
and digits
Recommendations
Avoid using all
uppercase letters
Avoid starting with
an underscore
Avoid using abbreviations
Use PascalCasing naming
in multiple-word names
different
Different
Answer42
42Answer
BADSTYLE
_poorstyle
BestStyle
Msg
Message
37.
C# Keywords
Keywordsare reserved identifiers
Do not use keywords as variable names
Results in a compile-time error
Avoid using keywords by changing their case sensitivity
abstract, base, bool, default, if, finally
int INT; // Poor style
38.
Declaring Local Variables
Usually declared by data type and variable name:
Possible to declare multiple variables in
one declaration:
--or--
int itemCount;
int itemCount, employeeNumber;
int itemCount,
employeeNumber;
39.
Assigning Values toVariables
Assign values to variables that are already declared:
Initialize a variable when you declare it:
You can also initialize character values:
int employeeNumber;
employeeNumber = 23;
int employeeNumber = 23;
char middleInitial = 'J';
40.
Compound Assignment
Addinga value to a variable is very common
There is a convenient shorthand
This shorthand works for all arithmetic operators
itemCount = itemCount + 40;
itemCount += 40;
itemCount -= 24;
Increment and Decrement
Changing a value by one is very common
There is a convenient shorthand
This shorthand exists in two forms
itemCount += 1;
itemCount -= 1;
itemCount++;
itemCount--;
++itemCount;
--itemCount;
Enumeration Types
Definingan Enumeration Type
Using an Enumeration Type
Displaying an Enumeration Variable
enum Color { Red, Green, Blue }
Color colorPalette = Color.Red;
Console.WriteLine(“{0}”, colorPalette); // Displays Red
45.
Structure Types
Defininga Structure Type
Using a Structure Type
Employee companyEmployee;
companyEmployee.firstName = "Joe";
companyEmployee.age = 23;
public struct Employee
{
public string firstName;
public int age;
}
46.
Converting DataTypes
Implicit Data Type Conversion
Explicit Data Type Conversion
47.
Implicit Data TypeConversion
To Convert int to long:
Implicit conversions cannot fail
May lose precision, but not magnitude
using System;
class Test
{
static void Main( )
{
int intValue = 123;
long longValue = intValue;
Console.WriteLine("(long) {0} = {1}", intValue,
longValue);
}
}
48.
Explicit Data TypeConversion
To do explicit conversions, use a cast expression:
using System;
class Test
{
static void Main( )
{
long longValue = Int64.MaxValue;
int intValue = (int) longValue;
Console.WriteLine("(int) {0} = {1}", longValue,
intValue);
}
}
What Is anArray?
An array is a sequence of elements
All elements in an array have the same type
Structs can have elements of different types
Individual elements are accessed using integer indexes
Integer index 0
(zero)
Integer index 4
(four)
51.
Array Notation inC#
You declare an array variable by specifying:
The element type of the array
The rank of the array
The name of the variable
This specifies the rank of the array
This specifies the name of the array variable
This specifies the element type of the array
type[ ] name;
52.
Array Rank
Rankis also known as the array dimension
The number of indexes associated with each element
Rank 1: One-dimensional
Single index associates with
each long element
Rank 2: Two-dimensional
Two indexes associate with
each int element
long[ ] row; int[,] grid;
53.
Accessing Array Elements
Supply an integer index for each rank
Indexes are zero-based
3
3
2
2
1
1
long[ ] row;
...
row[3];
int[,] grid;
...
grid[1,2];
54.
Creating Array Instances
Declaring an array variable does not create an array!
You must use new to explicitly create the array instance
Array elements have an implicit default value of zero
row
0 0 0 0
grid
0 0 0
0 0 0
Variable Instance
long[ ] row = new long[4];
int[,] grid = new int[2,3];
55.
Initializing Array Elements
The elements of an array can be explicitly initialized
You can use a convenient shorthand
row
0 1 2 3
Equivalent
long[ ] row = new long[4] {0, 1, 2, 3};
long[ ] row = {0, 1, 2, 3};
56.
Initializing Multidimensional ArrayElements
You can also initialize multidimensional array elements
All elements must be specified
grid
5 4 3
2 1 0
Implicitly a new int[2,3] array
int[,] grid = {
{5, 4, 3},
{2, 1, 0}
};
int[,] grid = {
{5, 4, 3},
{2, 1 }
};
57.
Creating a ComputedSize Array
The array size does not need to be a compile-time
constant
Any valid integer expression will work
Accessing elements is equally fast in all cases
Array size specified by compile-time integer constant:
Array size specified by run-time integer value:
long[ ] row = new long[4];
string s = Console.ReadLine();
int size = int.Parse(s);
long[ ] row = new long[size];
58.
Copying Array Variables
Copying an array variable copies the array variable only
It does not copy the array instance
Two array variables can refer to the same array instance
copy
row
0 0 0 0
Variable Instance
long[ ] row = new long[4];
long[ ] copy = row;
...
row[0]++;
long value = copy[0];
Console.WriteLine(value);
Overview
Introduction toStatements
Using Selection Statements
Using Iteration Statements
Using Jump Statements
61.
Introduction toStatements
Statement Blocks
Types of Statements
62.
Statement Blocks
Usebraces As
block delimiters
{
// code
}
{
int i;
...
{
int i;
...
}
}
{
int i;
...
}
...
{
int i;
...
}
A block and its
parent block
cannot have a
variable with
the same name
Sibling blocks
can have
variables with
the same name
63.
Types of Statements
SelectionStatements
The if and switch statements
Iteration Statements
The while, do, for, and foreach statements
Jump Statements
The goto, break, and continue statements
64.
The if Statement
Syntax:
No implicit conversion from int to bool
int x;
...
if (x) ... // Must be if (x != 0) in C#
if (x = 0) ... // Must be if (x == 0) in C#
if ( Boolean-expression )
first-embedded-statement
else
second-embedded-statement
65.
Cascading if Statements
enumSuit { Clubs, Hearts, Diamonds, Spades }
Suit trumps = Suit.Hearts;
if (trumps == Suit.Clubs)
color = "Black";
else if (trumps == Suit.Hearts)
color = "Red";
else if (trumps == Suit.Diamonds)
color = "Red";
else
color = "Black";
66.
The switch Statement
Use switch statements for multiple case blocks
Use break statements to ensure that no fall
through occurs
switch (trumps) {
case Suit.Clubs :
case Suit.Spades :
color = "Black"; break;
case Suit.Hearts :
case Suit.Diamonds :
color = "Red"; break;
default:
color = "ERROR"; break;
}
67.
The while Statement
Execute embedded statements based on Boolean value
Evaluate Boolean expression at beginning of loop
Execute embedded statements while Boolean value
Is True
int i = 0;
while (i < 10) {
Console.WriteLine(i);
i++;
}
0 1 2 3 4 5 6 7 8 9
68.
The do Statement
Execute embedded statements based on Boolean value
Evaluate Boolean expression at end of loop
Execute embedded statements while Boolean value
Is True
int i = 0;
do {
Console.WriteLine(i);
i++;
} while (i < 10);
0 1 2 3 4 5 6 7 8 9
69.
The for Statement
Place update information at the start of the loop
Variables in a for block are scoped only within the block
A for loop can iterate over several values
for (int i = 0; i < 10; i++) {
Console.WriteLine(i);
}
0 1 2 3 4 5 6 7 8 9
for (int i = 0; i < 10; i++)
Console.WriteLine(i);
Console.WriteLine(i); // Error: i is no longer in scope
for (int i = 0, j = 0; ... ; i++, j++)
70.
The foreach Statement
Choose the type and name of the iteration variable
Execute embedded statements for each element of the
collection class
ArrayList numbers = new ArrayList( );
for (int i = 0; i < 10; i++ ) {
numbers.Add(i);
}
foreach (int number in numbers) {
Console.WriteLine(number);
}
0 1 2 3 4 5 6 7 8 9
71.
Using JumpStatements
The goto Statement
The break and continue Statements
72.
The goto Statement
Flow of control transferred to a labeled statement
Can easily result in obscure “spaghetti” code
if (number % 2 == 0) goto Even;
Console.WriteLine("odd");
goto End;
Even:
Console.WriteLine("even");
End:;
73.
The break andcontinue Statements
The break statement jumps out of an iteration
The continue statement jumps to the next iteration
int i = 0;
while (true) {
Console.WriteLine(i);
i++;
if (i < 10)
continue;
else
break;
}
Defining Methods
Mainis a method
Use the same syntax for defining your own methods
using System;
class ExampleClass
{
static void ExampleMethod( )
{
Console.WriteLine("Example method");
}
static void Main( )
{
// ...
}
}
77.
Calling Methods
Afteryou define a method, you can:
Call a method from within the same class
Use method’s name followed by a parameter list in
parentheses
Call a method that is in a different class
You must indicate to the compiler which class contains
the method to call
The called method must be declared with the public
keyword
Use nested calls
Methods can call methods, which can call other
methods, and so on
78.
Using the returnStatement
Immediate return
Return with a conditional statement
static void ExampleMethod( )
{
int numBeans;
//...
Console.WriteLine("Hello");
if (numBeans < 10)
return;
Console.WriteLine("World");
}
79.
Using Local Variables
Local variables
Created when method begins
Private to the method
Destroyed on exit
Shared variables
Class variables are used for sharing
Scope conflicts
Compiler will not warn if local and class names clash
80.
Returning Values
Declarethe method with non-void type
Add a return statement with an expression
Sets the return value
Returns to caller
Non-void methods must return a value
static int TwoPlusTwo( ) {
int a,b;
a = 2;
b = 2;
return a + b;
}
int x;
x = TwoPlusTwo( );
Console.WriteLine(x);
81.
Declaring and CallingParameters
Declaring parameters
Place between parentheses after method name
Define type and name for each parameter
Calling methods with parameters
Supply a value for each parameter
static void MethodWithParameters(int n, string y)
{ ... }
MethodWithParameters(2, "Hello, world");
82.
Pass by Value
Default mechanism for passing parameters:
Parameter value is copied
Variable can be changed inside the method
Has no effect on value outside the method
Parameter must be of the same type or compatible type
static void AddOne(int x)
{
x++; // Increment x
}
static void Main( )
{
int k = 6;
AddOne(k);
Console.WriteLine(k); // Display the value 6, not 7
}
83.
Pass by Reference
What are reference parameters?
A reference to memory location
Using reference parameters
Use the ref keyword in method declaration and call
Match types and variable values
Changes made in the method affect the caller
Assign parameter value before calling the method
84.
Output Parameters
Whatare output parameters?
Values are passed out but not in
Using output parameters
Like ref, but values are not passed into the method
Use out keyword in method declaration and call
static void OutDemo(out int p)
{
// ...
}
int n;
OutDemo(out n);
85.
Using Variable-Length ParameterLists
Use the params keyword
Declare as an array at the end of the parameter list
Always pass by value
static long AddList(params long[ ] v)
{
long total, i;
for (i = 0, total = 0; i < v.Length; i++)
total += v[i];
return total;
}
static void Main( )
{
long x = AddList(63,21,84);
}
86.
Declaring Overloaded Methods
Methods that share a name in a class
Distinguished by examining parameter lists
class OverloadingExample
{
static int Add(int a, int b)
{
return a + b;
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
static void Main( )
{
Console.WriteLine(Add(1,2) + Add(1,2,3));
}
}
87.
Method Signatures
Methodsignatures must be unique within a class
Signature definition
Name of method
Parameter type
Parameter modifier
Forms Signature
Forms Signature
Definition
Definition
Name of parameter
Return type of method
No Effect on
No Effect on
Signature
Signature
Overview
Classes andObjects
Using Encapsulation
C# and Object Orientation
Defining Object-Oriented Systems
90.
Classes andObjects
What Is a Class?
What Is an Object?
Comparing Classes to Structs
Abstraction
91.
What Is aClass?
For the philosopher…
An artifact of human classification!
Classify based on common behavior or attributes
Agree on descriptions and names of useful classes
Create vocabulary; we communicate; we think!
For the object-oriented programmer…
A named syntactic construct that describes common
behavior and attributes
A data structure that includes both data and functions
CAR?
92.
What Is anObject?
An object is an instance of a class
Objects exhibit:
Identity: Objects are distinguishable from one another
Behavior: Objects can perform tasks
State: Objects store information
93.
Comparing Classes toStructs
A struct is a blueprint for a value
No identity, accessible state, no added behavior
A class is a blueprint for an object
Identity, inaccessible state, added behavior
struct Time class BankAccount
{ {
public int hour; ...
public int minute; ...
} }
94.
Controlling Access Visibility
Methods are public, accessible from the outside
Data is private, accessible only from the inside
Withdraw( )
Deposit( )
balance
Withdraw( )
Deposit( )
balance
BankAccount ?
BankAccount ?
95.
Using Static Data
Static data describes information for all objects
of a class
For example, suppose all accounts share the same
interest rate. Storing the interest rate in every account
would be a bad idea. Why?
Withdraw( )
Deposit( )
balance 12.56
interest 7%
Withdraw( )
Deposit( )
balance 99.12
interest 7%
96.
Using Static Methods
Static methods can only access static data
A static method is called on the class, not the object
InterestRate( )
interest 7%
Withdraw( )
Deposit( )
balance 99.12
owner "Fred"
An account object
The account class
Classes contain static data and
static methods
Objects contain object data and
object methods
97.
Defining Simple Classes
Data and methods together inside a class
Methods are public, data is private
class BankAccount
{
public void Withdraw(decimal amount)
{ ... }
public void Deposit(decimal amount)
{ ... }
private decimal balance;
private string name;
}
Public methods
describe
accessible
behaviour
Private fields
describe
inaccessible
state
98.
Instantiating New Objects
Declaring a class variable does not create an object
Use the new operator to create an object
class Program
{
static void Main( )
{
Time now;
now.hour = 11;
BankAccount yours = new BankAccount( );
yours.Deposit(999999M);
}
}
hour
minute
now
yours ...
...
new
BankAccount
object
99.
Using the thisKeyword
The this keyword refers to the object used to call the
method
Useful when identifiers from different scopes clash
class BankAccount
{
...
public void SetName(string name)
{
this.name = name;
}
private string name;
}
If this statement were
name = name;
What would happen?
100.
Creating Nested Classes
Classes can be nested inside other classes
class Program
{
static void Main( )
{
Bank.Account yours = new Bank.Account( );
}
}
class Bank
{
... class Account { ... }
}
The full name of the nested
class includes the name of
the outer class
101.
Accessing Nested Classes
Nested classes can also be declared as public or private
class Bank
{
public class Account { ... }
private class AccountNumberGenerator { ... }
}
class Program
{
static void Main( )
{
Bank.Account accessible;
Bank.AccountNumberGenerator inaccessible;
}
}
102.
Inheritance
Inheritance specifiesan “is a kind of" relationship
Inheritance is a class relationship
New classes specialize existing classes
Musician
Violin
Player
Base class
Derived class
Generalization
Specialization Is this a good
example of
inheritance ?
103.
Single and MultipleInheritance
Single inheritance: deriving from one base class
Multiple inheritance: deriving from two or more base
classes
Stringed
Instrument
Violin
Musical
Instrument
Stringed
Instrument
Pluckable
Violin has a single direct
base class
Stringed Instrument has
two direct base classes
104.
Polymorphism
The methodname resides in the base class
The method implementations reside in the
derived classes
String Musician
TuneYourInstrument( )
Guitar Player
TuneYourInstrument( )
Violin Player
TuneYourInstrument( )
A method with no
implementation is
called an operation
105.
Abstract Base Classes
Some classes exist solely to be derived from
It makes no sense to create instances of these classes
These classes are abstract
Stringed Musician
{ abstract }
Guitar Player
« concrete »
Violin Player
« concrete »
You can create instances
of concrete classes
You cannot create instances
of abstract classes
106.
Interfaces
Interfaces containonly operations, not implementation
String Musician
{ abstract }
Violin Player
« concrete »
Musician
« interface »
Nothing but operations.
You cannot create instances
of an interface.
May contain some implementation.
You cannot create instances
of an abstract class.
Must implement all inherited operations.
You can create instances
of a concrete class.
107.
Early and LateBinding
Normal method calls are resolved at compile time
Polymorphic method calls are resolved at run time
Musician
« interface »
Violin Player
« concrete »
Late binding
Early binding
runtime
TuneYourInstrument( )
TuneYourInstrument( )