Object and delegate creation new T...{...} Object creation with initializer checkedx Evaluate expression in checked context uncheckedx Evaluate expression in unchecked context defaultT O
Trang 1Hoang Anh Viet
VietHA@it-hut.edu.vn
HaNoi University of Technology
Chapter 2 Core C#
Programming Constructs
Trang 2Objectives
“This chapter surveys the C# language syntax I introduce you to the two fundamental kinds of types within the CLR: value types and reference types This chapter also describes namespaces and how you can use them to logically partition types and functionality within your applications.”
2
Trang 32.1 C# Is a strongly Typed Language
2.2 Expression
2.3 Statements and Expressions
2.4 Types and Variabless
2.5 NameSpaces
2.6 Control Flows
Trang 42.1 C# Is a strongly Typed Language
Every variable and object instance in the system is of a well-defined type
This enables the compiler to check that the operations to perform on variables and object instance are valid
It is always best to find bugs at compile time rather than run time
Example:
• Method ComputeAvg(): computes the average of two integers and returns the result
4
Trang 5double ComputeAvg( int param1, int param2 )
complain and stop
Convert objects into integers
Trang 6Roadmap
2.1 C# Is a strongly Typed Language
2.2 Expression
2.3 Statements and Expressions
2.4 Types and Variabless
2.5 NameSpaces
2.6 Control Flows
6
Trang 72.2 Expressions
Expressions in C# are identical to expressions in C++ and
Java.
Are built using operands, eg variables or types within an
application, and operators
Operators can be overloaded
Operators can have different meaning in different contexts
• Eg: the + operator can mean string concatenation using with string operands
C# operator precedence:
• When an expression contains multiple operators, the precedence of the
operators controls the order in which the individual operators are evaluated
• Entries at the top of the table have higher precedence
• Operators within the same category have equal precedence
Trang 8new T( ) Object and delegate creation
new T( ){ } Object creation with initializer
checked(x) Evaluate expression in checked context
unchecked(x) Evaluate expression in unchecked context
default(T) Obtain default value of type T
delegate { } Anonymous function (anonymous method)
8
Trang 9Category Expression Description
Additive x + y Addition, string concatenation, delegate combination
x – y Subtraction, delegate removal
x >> y Shift right
Trang 10x as T Return x typed as T, or null if x is not a T
Logical AND x & y Integer bitwise AND, boolean logical AND
10
Trang 11 2.1 C# Is a strongly Typed Language
2.2 Expression
2.3 Statements and Expressions
2.4 Types and Variabless
2.5 NameSpaces
2.6 Control Flows
Trang 122.3 Statements and Expressions
The actions of a program are expressed using
statements
Several different kinds of statements:
A block: consists of a list of statements written between the
Trang 13Statements and Expressions(2)
Epression statements are used to evaluate expressions
Selection statements are used to select one of a number of
possible statements for execution based on the value of some expression – if, switch
Iteration statements are used to repeatedly execute an
embedded statement – while , do , for , foreach
while (i ++< Length) {
if (continue == true ) {x=69;}
else {x=96;}
Console WriteLine(“Goodbye”);
Trang 14Statements and Expressions(3)
Jump statements are used to transfer control - break,
continue, goto, throw, return, and yield
The try catch statement is used to catch exceptions that occur during execution of a block, and the try finally
statement is used to specify finalization code that is always executed, whether an exception occurred or not
Trang 15Statements and Expressions(4)
The checked and unchecked statements are used to control the overflow checking context for integral-type arithmetic
operations and conversions
The lock statement is used to obtain the mutual-exclusion lock for a given object, execute a statement, and then release the lock
The using statement is used to obtain a resource, execute a
statement, and then dispose of that resource
Trang 16Roadmap
2.1 C# Is a strongly Typed Language
2.2 Expression
2.3 Statements and Expressions
2.4 Types and Variabless
2.5 NameSpaces
2.6 Control Flows
16
Trang 17Value Types and Reference Types
• Living place: on the heap
• Variables used to manipulate them are references to objects on the managed heap
Trang 18Value Types
Contain directly their value and are customarily created statically
Initialization: using the new statement
Derive from System.ValueType
Primitives: int, float, char and bool
Others: enum, struct
18
Trang 19Reference Types
The lifetime of the resulting object is controlled be
garbage collection services provided by CLR
The reference holds the location of an object created on the managed heap
Derive from System.Object and created with the new
keyword
Types: interfaces, arrays and delegates
Trang 20s "Hello world"
Value Type
Reference
Type
20
Trang 21Value Types contain Reference Types
Example:
class ShapeInfo {
public string infoString;
public ShapeInfo(string info) { infoString = info; }
}
Reference type
Trang 22struct Rectangle
{
public ShapeInfo rectInfo;
public int rectTop, rectLeft, rectBottom, rectRight;
public Rectangle(string info, int top, int left, int bottom, int right)
{
rectInfo = new ShapeInfo(info);
rectTop = top; rectBottom = bottom;
rectLeft = left; rectRight = right;
22
Trang 23static void ValueTypeContainingRefType()
Console.WriteLine( "-> Changing values of r2");
r2.rectInfo.infoString = "This is new info!";
Assign a new Rectangle to
r1
Change some values of r2 Print values
of both
Trang 24Result:
24
Trang 25Default Variable Initialization
The following categories of variables are automatically initialized to their default values:
For a variable of a value-type, the default value is the
same as the value computed by the value-type’s default
constructor
Trang 26Default Variable Initialization(2)
Value-type’s default constructor:
All value types implicitly declare a public parameterless instance
constructor called the default constructor
Default constructor returns the default value for the value type:
26
sbyte, byte, short, ushort, int, uint, long, and ulong 0
26
Trang 27Default Variable Initialization(3)
float 0.0f
double 0.0d
decimal 0.0m
enum-type E 0, converted to the type E
struct-type All value type fields: default value of
Value Type All reference type fields: null
Trang 28Implicitly Typed Local Variables
“In C#, every variable declared in the code must have an explicit type associated with it But sometimes, when writing code for strongly typed languages, the amount of typing needed to declare such variables can be tedious…”
28
Trang 29Implicitly Typed Local Variables(2)
var is a new keyword in C# 3.0
Declaring a local variabl using the new var keyword asks the compiler to reserve a local memory slot and attach
an inferred type to that slot
At compilation time, compiler can initialize variables
without asking the type explicitly
How to use:
var localVariant = <expression>
localVariant is init with type of <expression>
Trang 30var newValue; // emits error CS0818
var a = 2, b = 1;
var x, y = 4;
Not permited
30
Trang 31Implicitly Typed Local Variables(3)
Restriction:
var cannot use with multiple variable declarators
var x=69, y=9.6; //Error, Implicitly-typed local variables cannot have
multiple declarators
Declarator implicitly typed local variables must include a
local-variable-initializer
var x; //Error, no initializer to infer type from
The local-variable-initializer must be an expression
The initializer expression must have a compile-time type
var u = x => x + 1; //Error, anonymous functions do not have a type
The initializer expression cannot refer to the declared variable itself
Trang 32long value = defaultValue;
int smallerValue = (int) value;
public class EntryPoint {
static void Main() {
Trang 33Implicit Conversions
One type of data is automatically converted into another type of data
No data loss
Implicit Numerical Conversion
Implicit Enumeration Conversion
Permit the decimal, integer, literal to be converted to any enum
1 long x;
2 int y = 25;
3 x = y; //implicit numerical conversion
Trang 34Implicit Conversions(2)
Implicit Reference Conversion
From any reference type to object
From any class type D to any class type B, provided D is inherited from B.
From any class type A to interface type I, provided A implements I
From any interface type I2 to any other interface type I1, provided I2 inherits I1
From any array type to System.Array
From any array type A with element type a to an array type B with element type b provided A & B differ only in element type (but the same number of elements) and both a and b are reference types and an implicit reference conversion exists between a & b.
From any delegate type to System.Delegate type
From any array type or delegate type to System.ICloneable
From null type to any reference type
34
Trang 36Explicit Conversions
Using the casting operator ()
May be loss data
Explicit Numerical Conversions
Explicit Enumeration Conversions
From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double
or decimal to any enum type
From any enum type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double or decimal
From any enum type to any other enum type
36
Trang 37Explicit Conversions(2)
Explicit Reference Conversions
From object to any reference type
From any class type B to any class type D, provided B is the base class of D
From any class type A to any interface type I, provided S is not sealed and
From System.Array to any array type
From System.Delegate type to any delegate type
From System.ICloneable to any array or delegate type.
Trang 38as and is Operators
The as operator
is used to perform conversions between compatible reference types
The as operator is like a cast operation However, if the conversion
is not possible, as returns null instead of raising an exception
The is operator
Checks if an object is compatible with a given type
An is expression evaluates to true if the provided expression is null, and the provided object can be cast to the provided type
non-without causing an exception to be thrown
The is operator only considers reference conversions, boxing
conversions, and unboxing conversions
38
Trang 39 Support for generics is one of the most exciting new
additions to the C# language
Using the generic can define a type that depends upon another type that is not specified at the point of definition
Example:
A collection may be a list, queue or stack…
Trang 401 public class List
3 private object[] elements;
4 private int count;
5.
6 public void Add(object element) {
7 if (count == elements.Length) Resize(count*2);
8 elements[count++] = element;
9 }
10.
11 public object this[int index] {
12 get { return elements[index]; }
13 set { elements[index] = value; }
14 }
15.
16 public int Count {
17 get { return count; }
18 }
19 }
1 public class List <ItemType>
3 private ItemType [] elements;
4 private int count;
5.
6 public void Add( ItemType element) {
7 if (count == elements.Length) Resize(count*2);
8 elements[count++] = element;
9 }
10.
11 public ItemType this[int index] {
12 get { return elements[index]; }
13 set { elements[index] = value; }
14 }
15.
16 public int Count {
17 get { return count; }
3 intList.Add(1); // Argument is boxed
4 intList.Add(2); // Argument is boxed
5 intList.Add("Three"); // Should be an error 6.
7 int i = (int)intList[0]; // Cast required
1 List < int > intList = new List < int >();
Trang 41 Why generics?
Type checking, no boxing, no downcasts
Reduced code bloat (typed collections)
How are C# generics implemented?
Instantiated at run-time, not compile-time
Checked at declaration, not instantiation
Work for both reference and value types
Complete run-time type information
Trang 42Generics(3)
Can be used with various types
Class, struct, interface and delegate
Can be used with methods, parameters and return types
Support the concept of constraints
One base class, multiple interfaces, new()
42
Trang 43 Type parameters can be applied to
Class, struct, interface, and delegate types
class Dictionary<KeyType, ValueType> { }
struct Pair<FirstType, SecondType> { }
Trang 441 class Array
3 public static T[] Create<T>(int size) {
4 return new T[size];
Type parameters can be applied to
Class, struct, interface, and delegate types
Methods
44
Trang 451 interface IComparable{int CompareTo(object obj);} 2.
1 interface IComparable{int CompareTo(object obj);}
2 class Dictionary<K, V> where K: IComparable
One base class, multiple interfaces, new()
Specified using “where” clause
Trang 46Roadmap
2.1 C# Is a strongly Typed Language
2.2 Expression
2.3 Statements and Expressions
2.4 Types and Variabless
2.5 NameSpaces
2.6 Control Flows
46
Trang 472.5 Namespaces
Need for Namespaces
Using namespace directives
Using alias directives
Standard Namespaces in NET
Trang 48Need for Namespaces
Namespaces allow you to create a system to organize your code
A good way to organize your namespaces is via a
hierarchical system
Placing code in different sub-namespaces can keep your code organized
Create an alias for a namespace (a using alias)
Permit the use of types in a namespace, such that, you do not have
to qualify the use of a type in that namespace (a using directive).
48
Trang 49Using namespace directives
If not use using System;
you must use method
Trang 50Using alias directives
using identifier = namespace-or-type-name ;
Trang 51Standard Namespaces in NET
Trang 52Standard Namespaces in NET(2)
Windows Presentation Foundation
Trang 53Standard Namespaces in NET(3)
Communications and Workflow
Trang 54Roadmap
2.1 C# Is a strongly Typed Language
2.2 Expression
2.3 Statements and Expressions
2.4 Types and Variabless
2.5 NameSpaces
2.6 Control Flows
54
Trang 56statement(s)_2] //The alternative result
condition is a relational or logical expression.
statement(s)_1 is a statement (or a block of statements) that is
executed if the condition is true.
statement(s)_2 is a statement (or a block of statements) that is
executed if the condition is false
56
2 Console.Write("Salary is greater than 2k");
2 Console.Write("Salary is greater than 2k");
// The original result
3 else
to 2k"); // The alternative result
Trang 57Nested if-else Statements
Trang 58jump-statement case constant-3:
[default: statement(s);
jump-statement]
}
switch Construct expression represents a value that corresponds to the
associated switch choice
statement(s) is a statement or block
of statements that
is executed if the corresponding condition is evaluated true
jump-statement is a branching
statement to transfer control outside the specific case, such as
break or goto (explained later)
default deals with all the other cases