Visual Week 2
Visual Week 2
Fundamentals of the
Types, program structure, statements, operators
C# language
Learning
Objectives Be able to begin
Using the .NET Framework SDK
writing and
debugging C# Using Visual Studio.NET
programs
Be able to write
individual C#
methods
Design Goals
Hello World Types
of C#
Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
Hello World
Console.WriteLine("Hello
world");
• Console.ReadLine(); // Hit } }
enter to finish
Design Goals
Hello World Types
of C#
Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
Design Goals of C#
The Big Ideas
What is a component?
In general, component writer and
Coarser-grained than objects
An independent module of reuse user don’t know each other, don’t
(objects are language-level Includes multiple classes Often language-independent
and deployment work for the same company, and
constructs)
don’t use the same language
Component concepts are first class
Design Goals
• Properties, methods, events
of C# • Design-time and run-time attributes
Component- • Integrated documentation using XML
Orientation
Enables “one-stop programming”
Exceptions
Versioning
Avoid common
E.g. if (x = y) ...
errors
One-stop
Fewer moving parts
programming
Design Goals of C#
Preserving Your Investment
Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
A C# program is a collection of types
Can convert
from one type Implicitly and explicitly
to another
Types are
arranged in a
hierarchy
Types
Unified Type System
Reference types
• Root object
• String string
• Classes class Foo: Bar, IFoo {...}
• Interfaces interface IFoo: IBar {...}
• Arrays string[] a = new string[10];
• Delegates delegate void Empty();
Value Reference
(Struct) (Class)
Variable Memory
Actual value
holds location
Stack,
Allocated on Heap
member
Types Nullability
Always has
value
May be null
Assignment Copy
Copy data
means reference
Types • Benefits of value types
• No heap allocation, less GC pressure
Unified Type • More efficient use of memory
System • Less reference indirection
• Unified type system
• No primitive/object dichotomy
Implicit conversions
• Occur automatically
• Guaranteed to succeed
• No information (precision) loss
Value Reference
Integral types object
Floating point types string
decimal
bool
char
Predefined Types
Value Types
• All are predefined structs
Character char
Logical bool
Predefined Types
Integral Types
All integer types can be implicitly converted Conversions between decimal and floating s * m * 10e
to a decimal type types require explicit conversion due to
possible loss of precision
s = 1 or –1
0 m 296
-28 e 0
Predefined Types
Integral Literals
• Integer literals can be expressed as decimal
or hexadecimal
• U or u: uint or ulong
• L or l: long or ulong
• UL or ul: ulong
123 // Decimal
0x7B // Hexadecimal
123U // Unsigned
123ul // Unsigned long
123L // Long
Predefined Types
Real Literals
• F or f: float
• D or d: double
• M or m: decimal
123f // Float
123D // Double
123.456m // Decimal
1.23e2f // Float
12.3E1M // Decimal
Predefined Types
bool
• Represents logical values
• Literal values are true and false
• Cannot use 1 and 0 as boolean values
• No standard conversion between other types
and bool
Predefined
Types protected void
object Public
public void Object()
Finalize()
Methods
protected object public int
MemberwiseClone() GetHashCode()
public System.Type
GetType()
Predefined Types
string
• An immutable sequence of Unicode characters
• Reference type
• Special syntax for literals
• string s = “I am a string”;
string s2 = @“\\server\fileshare\filename.cs”;
Types
User-defined Types
• User-defined types
Enumerations enum
Interface interface
An enum defines a type name Choices must be known at Strongly typed Can specify underlying type
for a related group of symbolic compile-time
constants
No implicit conversions to/from int byte, sbyte, short, ushort, int, uint, long,
Can be explicitly converted ulong
Operators: +, -, ++, --, &, |, ^, ~, …
Types
Enums
Color c = Color.Black;
Console.WriteLine(c); // 0
Console.WriteLine(c.Format()); // Black
• All enums derive from System.Enum
• Provides methods to
Types • determine underlying type
• test if a value is supported
Enums • initialize from string constant
• retrieve all values in enum
• …
Types
Arrays
• Arrays allow a group of elements of a specific
type to be stored in a contiguous block of
memory
• Arrays are reference types
• Derived from System.Array
• Zero-based
• Can be multidimensional
• Arrays know their length(s) and rank
• Bounds checking
Types
Arrays
prime2[i] = prime[i];
Contain no implementation
Member access
10
sp
20
cp CPoint
10
20
Types
Delegates
A delegate is a reference type that When instantiated, a delegate holds Foundation for framework events
defines a method signature one or more methods
Essentially an object-oriented function pointer
Agenda
Hello World
Design Goals of C#
Types
Program Structure
Statements
Operators
Using Visual Studio.NET
Using the .NET Framework SDK
Organizing Types
Namespaces
Program
Structure References
Overview
Main Method
Syntax
Program • Physical organization Assembly
Structure • Types are defined in
files Module
Organizing • Files are compiled File
into
Types modules Type
• Modules are
grouped
into assemblies
Types are defined in files
class C1 {
} }
//
N1.C1
class C2 {
//
} } }
N1.C1.C2
• The using statement lets you • using N1;
Program use types without typing the
Structure fully qualified name
• C1 a; //
• Can always use a fully The N1. is implicit
Namespaces qualified name • N1.C1 b; //
Fully qualified name
• C2 c; //
Error! C2 is undefined
• N1.N2.C2 d; //
One of the C2 classes
• C1.C2 e; //
The other one
• The using statement also lets • using C1 = N1.N2.C1;
Program you create aliases • using N2 = N1.N2;
Structure
• C1 a;
Namespaces Refers to N1.N2.C1
//
• N2.C1 b; //
Refers to N1.N2.C1
Best practice: Put all of your
types in a unique namespace
Program
Have a namespace for your
Structure company, project, product,
etc.
Namespaces
Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
• High C++ fidelity • void Foo() {
Statements • if, while, do require bool • i == 1; // error
Overview condition • }
• goto can’t jump into blocks
• switch statement
• No fall-through
• foreach statement
• checked and unchecked
statements
• Expression
statements
must do work
Statement lists
Block statements
Loop Statements
Labeled statements
◼ while
Declarations ◼ do
◼ for
Statements • Constants
• Variables
◼ foreach
Jump Statements
Overview Expression statements
◼ break
◼
• checked, uncheckedcontinue
• lock ◼ goto
• using ◼ return
◼ throw
Conditionals
Exception handling
• if ◼ try
• switch ◼ throw
Statements are terminated with a
semicolon (;)
Statements
Syntax Just like C, C++ and Java
*/
• Statement list: one or more • static void Main() {
Statements statements in sequence • F();
Statement • Block statement: a
statement list delimited by
• G();
• { // Start block
Lists & Block braces { ... }
• H();
Statements •
•
; // Empty statement
I();
• } // End block
• }
Statements
Variables and Constants
Console.WriteLine(pi
static void Main() { const float pi = 3.14f; const int r = 123; int a;
* r * r);
Console.WriteLine(a
int b = 2, c = 3; a = 1; }
+ b + c);
Statements
Variables and • The scope of a variable or constant runs
from the point of declaration to the end of
Constants the enclosing block
• Within the scope of a
variable or constant it
is an error to declare
another variable or
constant with the same
name
• {
• int x;
• {
Statements • int x; // Error: can’t
hide variable x
Variables and Constants • }
• }
• Variables must be assigned a value
before they can be used
• Explicitly or automatically
• Called definite assignment
• Automatic assignment occurs for
static fields, class instance fields and
array elements
• void Foo() {
• string s;
Statements • Console.WriteLine(s); //
Error
Variables • }
• goto can be used to
transfer control within
or out of a block, but
not into a nested block
Statements •
•
for (i = 0; i < values.GetLength(0); i++)
for (j = 0; j < values.GetLength(1); j++)
goto •
•
found:
row = i; col = j;
• }
• Statements must do
work
• Assignment,
method call, ++, --,
new
switch
Statement
Must explicitly state how to end case
Statements •
•
case “fastest”:
case “winner”:
switch •
•
result = 1; break;
case “runner-up”:
Statement •
•
result = 2; break;
default:
• result = 0;
• }
• return result;
• }
Statements
while Statement
• Requires bool expression
int i = 0;
while (i < 5) {
...
i++;
} int i = 0;
do {
...
i++;
}
while (i < 5);
while (true) {
...
}
Statements
for Statement
Jump
• End iteration of inner-most loop
Statements continue
return
• Exit a method
[<expression>]
catch block handles exceptions Can have multiple catch blocks to handle different kinds of exceptions
finally block contains code that Cannot use jump statements (e.g. goto)
will always be executed to exit a finally block
Statements
Exception Handling
throw statement raises an
exception
Statements •
•
catch (ArgumentNullException e) {
Console.WriteLine(“caught null argument");
Exception •
•
}
catch {
Handling •
• }
Console.WriteLine("catch");
• finally {
• Console.WriteLine("finally");
• }
• Multi-threaded applications have to protect
against concurrent access to data
• Must prevent data corruption
• The lock statement uses an instance to
Statements provide mutual exclusion
Synchronization • Only one lock statement can have access to
the same instance
• Actually uses the .NET Framework
System.Threading.Monitor class to
provide mutual exclusion
Statements
Synchronization
public class CheckingAccount {
decimal balance;
public void Deposit(decimal amount) {
lock (this) {
balance += amount;
}
}
public void Withdraw(decimal amount) {
lock (this) {
balance -= amount;
}
}
}
Statements C# uses automatic memory management (garbage collection)
Default is unchecked
Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
Operators
Overview
C# provides a fixed set of operators, whose meaning is defined for the predefined types
Categories are in order of decreasing precedence Operators in each category have the same precedence
Operators
Precedence
Category Operators
Grouping: (x)
Member access: x.y
Method call: f(x)
Indexing: a[x]
Post-increment: x++
Primary
Post-decrement: x—
Constructor call: new
Type retrieval: typeof
Arithmetic check on: checked
Arithmetic check off: unchecked
Operators
Precedence
Category Operators
Positive value of: +
Negative value of: -
Not: !
Unary Bitwise complement: ~
Pre-increment: ++x
Post-decrement: --x
Type cast: (T)x
Multiply: *
Multiplicative Divide: /
Division remainder: %
Operators
Precedence
Category Operators
Add: +
Additive
Subtract: -
Shift bits left: <<
Shift
Shift bits right: >>
Less than: <
Greater than: >
Less than or equal to: <=
Relational
Greater than or equal to: >=
Type equality/compatibility: is
Type conversion: as
Operators
Precedence
Category Operators
Equals: ==
Equality
Not equals: !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Logical AND &&
Logical OR ||
Operators
Precedence
Category Operators
Ternary
?:
conditional
=, *=, /=, %=, +=, -=, <<=, >>=,
Assignment
&=, ^=, |=
Operators
Associativity
1 2 3 4 5 6
Variables are int - stores integers double - stores floating char - stores single string - stores text, bool - stores values
containers for storing (whole numbers), point numbers, with characters, such as 'a' such as "Hello World". with two states: true
data values. In C#, without decimals, such decimals, such as or 'B'. Char values are String values are or false
there are as 123 or -123 19.99 or -19.99 surrounded by single surrounded by double
different types of quotes quotes
variables (defined with
different keywords),
for example:
C# Operators
Operators are used to perform operations on variables and
values.
C# Types
Types can be Can convert from one Types are organized There are two categories Types are arranged in a
instantiated: type to another of types: hierarchy
Call methods Implicitly and explicitly Namespaces, files, assemblies Value and referance
Get and set properties etc.
C# Types
Reference
Value types
types
Contain
Directly Cannot be
references to May be null
contain data null
objects
C# Data
Types
Default Values
Uses methods of the
Console class in the
System namespace
Console.ReadLine()
Input /
Output In C# The most widely
used methods are –
Console.WriteLine()
Fundamental
Types Of C#
C# divides data types into two fundamental categories
Value Types
Reference Types
Why Do We
callback is to handle button-clicking, menu-selection, and
mouse-moving activities. But the problem with this traditional
approach is that the callback functions were not type-safe. In the
Need .NET framework, callbacks are still possible using delegates with
a more efficient approach. However, delegates maintain three
Delegates? important pieces of information, as in the following:
• The parameters of the method.
• The address of the method it calls.
• The return type of the method.
A delegate is a solution for situations where you want to pass
Why Do We
methods around to other methods. You are so accustomed to
passing data to methods as parameters that the idea of passing
methods as an argument instead of data might sound a little
Need strange. However, there are cases where you have a method that
does something, for instance, invoking another method. You do
Delegates? not know at compile time what this second method is. That
information is available only at runtime; hence Delegates are the
device to overcome such complications.
Lambda Expressions
The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.
An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.
Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces.
When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events
asynchronously, see Calling Synchronous Methods Asynchronously.
In the .NET class library, events are based on the EventHandler delegate and the EventArgs base class.
Basic Event
Declaration
1 2 3 4 5
Define a delegate that Declare an event using Implement a method, Create a method in the Subscribe the event
matches the signature the delegate you within the provider subscriber class that handling method to
of the event handler defined. class, that raises the will handle the event the event.
method you want to event. (conforms to the
use. delegate).
C# Programming
Collections
C# collections perform all the data structure work.
Just like an array, a collection can also be used to
store objects with an advantage over an array.
Queue<T>
Elements can be added using the Enqueue()
method. Cannot use collection-initializer
syntax.