You are on page 1of 94



CLR and JIT compiling.

C#, like Java, is executed indirectly through an abstract computer architecture called the CLR.
CLR => Common Language Runtime. Abstract, but well defined.

C# programs are compiled to an IL.

Also called MSIL, CIL (Common Intermediate Language) or bytecode.

CLR and JIT compiling.

The CLR transforms the CIL to assembly instructions for a particular hardware architecture.
This is termed jiting or Just-in-time compiling. Some initial performance cost, but the jitted code is cached for further execution. The CLR can target the specific architecture in which the code is executing, so some performance gains are possible.

CLR and JIT compiling.

All .NET languages compile to the same CIL. Each language actually uses only a subset of the CIL. The least-common denominator is the Common Language Specification (CLS). So, if you want to use your C# components in Visual Basic you need to program to the CLS.

CLR versus CLI.

CLR is actually an implementation by Microsoft of the CLI (Common Language Infrastructure) . CLI is an open specification. CLR is really a platform specific implementation.

The CLR Architecture

Base Class Library Support Thread Support Type Checker Security Engine MSIL to Native Compilers (JIT) Code Manager Class Loader From MSDN COM Marshaler Exception Manager Debug Engine Garbage Collector (GC)

Common Language Infrastructure.

CLI allows for cross-language development. Four components:
Common Type System (CTS) Meta-data in a language agnostic fashion. Common Language Specification behaviors that all languages need to follow. A Virtual Execution System (VES).

Common Type System (CTS)

A specification for how types are defined and how they behave.
no syntax specified

A type can contain zero or more members:

Field Method Property Event

We will go over these more throughout the quarter.

Common Type System (CTS)

CTS also specifies the rules for visibility and access to members of a type:
Private Family Family and Assembly Assembly Family or Assembly Public

We will go over these more throughout the quarter.

Common Type System (CTS)

Other rules
Object life-time Inheritance Equality (through System.Object)

Common Type System (CTS)

Languages often define aliases For example
CTS defines System.Int32 4 byte integer C# defines int as an alias of System.Int32 C# aliases System.String as string.

Common Type System (CTS)


Common Language System

A specification of language features
how methods may be called when constructors are called subset of the types in CTS which are allowed

For example
Code that takes UInt32 in a public method UInt32 is not in the CLS

Can mark classes as CLS-compliant

not marked is assumed to mean not compliant

CLS versus CLR

CLR via C#, Jeffrey Richter

Built-in Types
int uint sbyte

CTS type (FCL name)

System.Int32 System.UInt32 System.SByte

CLS compliant
yes no no

short ushort long ulong float double

System.Int16 System.UInt16 System.Int64 System.UInt64 System.Single System.Double

yes no yes no yes yes

char string object

System.Char System.String System.Object

yes yes yes

Blittable types
Most of these types are blittable, meaning their memory layout is consistent across languages and hence, support interoperability. The types bool, char, object and string are not and must be Marshaled when using these between languages. Single dimensional arrays of blittable types are also blittable.

Programming in C#


Code contained in files called assemblies
code and metadata .exe or .dll as before Executable needs a class with a Main method:
public static void Main(string[] args)

local: local assembly, not accessible by others shared: well-known location, can be GAC strong names: use crypto for signatures
then can add some versioning and trust

PE executable file
Structure of PE file PE header Entry point address MS IL instructions Other initial settings native instructions e.g., x86 instructions

Metadata Type Tables Attributes Security

Manifests and Assemblies

First C# Program
using System; namespace Test

class ExampleClass { static void Main() { System.Console.WriteLine("Hello, world!"); } }


Constructions of Note
like import in Java: bring in namespaces

disambiguation of names like Internet hierarchical names and C++ naming

like in C++ or Java single inheritance up to object

Constructions of Note
static void Main()
Defines the entry point for an assembly. Four different overloads taking string arguments and returning ints.

Takes a formatted string: Composite Format Indexed elements: e.g., {0}
can be used multiple times only evaluated once

{index [,alignment][:formatting]}


Memory Locations for Data

Name Rules for creating an identifier
Combination of alphabetic characters (a-z and A-Z), numeric digits (0-9), and the underscore First character in the name may not be numeric No embedded spaces concatenate (append) words together Keywords cannot be used Use the case of the character to your advantage Be descriptive with meaningful names
C# Programming: From Problem Analysis to Program Design 26

Reserved Words in C#

C# Programming: From Problem Analysis to Program Design


Naming Convention
For Class, method, namespace, and property identifiers
First letter of each word capitalized

For Variables and Objects

First letter of identifier lowercase; first letter of subsequent concatenated words capitalized First letter of variable name indicates its data type (I int, f float, d double, b boolean (not used in text)

For Constant Literals

All letters of identifier in upper case Underscore between words of identifier name

C# Programming: From Problem Analysis to Program Design


Variables a value of a Area in computer memory where

particular data type can be stored
Declare a variable Allocate memory

Syntax Simple Declaration

type identifier; e.g.: double dTotSales;

Syntax Declaration &Compile-time initialization

type identifier = expression; e.g. double dTaxRate = .125;
C# Programming: From Problem Analysis to Program Design 29

Types, Classes, and Objects

C# has more than one type of number
int type is a whole number floating-point types can have a fractional portion

Types are actually implemented through classes

One-to-one correspondence between a class and a type Simple data type such as int, implemented as a class
C# Programming: From Problem Analysis to Program Design 30

Types, Classes, and Objects

Instance of a class object

A class includes more than just data

Encapsulation packaging of data and behaviors into a single or unitclass

C# Programming: From Problem Analysis to Program Design


Type, Class, and Object Examples

C# Programming: From Problem Analysis to Program Design


Predefined Data Types

Common Type System (CTS) Divided into two major categories

Figure 3-1 .NET common types

C# Programming: From Problem Analysis to Program Design 33

Value and Reference Types

Figure 3-2 Memory representation for value and reference types

C# Programming: From Problem Analysis to Program Design 34

Value Types
Fundamental or primitive data types

Figure 3-3 Value type hierarchy

C# Programming: From Problem Analysis to Program Design 35

Value Types (continued)

C# Programming: From Problem Analysis to Program Design


Integral Data Types

Primary difference
How much storage is needed Whether a negative value can be stored

C# Programming: From Problem Analysis to Program Design


Floating-point Types
May be in scientific notation with an exponent n.neP
3.2e+5 is equivalent to 320,000 1.76e-3 is equivalent to .00176

OR in standard decimal notation Default type is double

C# Programming: From Problem Analysis to Program Design


Examples of Floating-point Declarations

double extraPerson = 3.50; // extraPerson originally set // to 3.50 double averageScore = 70.0; // averageScore originally set // to 70.0 double priceOfTicket; // cost of a movie ticket double gradePointAverage; // grade point average float totalAmount = 23.57f; // note the f must be placed after // the value for float types

C# Programming: From Problem Analysis to Program Design


Decimal Types
Monetary data items As with the float, must attach the suffix m or M onto the end of a number to indicate decimal
Float attach f or F

decimal endowmentAmount = 33897698.26M; decimal deficit;
C# Programming: From Problem Analysis to Program Design 40

Boolean Variables
Based on true/false, on/off logic

Boolean type in C# bool

Does not accept integer values such as 0, 1, or 1
bool undergraduateStudent; bool moreData = true;

C# Programming: From Problem Analysis to Program Design


Reference type
Represents a string of Unicode characters
string studentName; string courseName = "Programming I"; string twoLines = Line1\nLine2;

C# Programming: From Problem Analysis to Program Design


Making Data Constant

Add the keyword const to a declaration Value cannot be changed Standard naming convention Syntax
const type identifier = expression;
const double TAX_RATE = 0.0675; const int SPEED = 70; const char HIGHEST_GRADE = A;
C# Programming: From Problem Analysis to Program Design 43

Assignment Statements
Used to change the value of the variable
Assignment operator (=)

variable = expression;

Expression can be:

Another variable Compatible literal value Mathematical equation Call to a method that returns a compatible value Combination of one or more items in this list

C# Programming: From Problem Analysis to Program Design

Examples of Assignment Statements

double accountBalance, weight; decimal amountOwed, deficitValue; bool isFinished; accountBalance = 4783.68; weight = 1.7E-3; //scientific notation may be used amountOwed = 3000.50m; // m or M must be suffixed to // decimal deficitValue = -322888672.50M; isFinished = false;
C# Programming: From Problem Analysis to Program Design 45

Examples of Assignment Statements (continued)

int count = 0, newValue = 25; string aSaying, fileLocation;
aSaying = First day of the rest of your life!\n "; fileLocation = @C:\CSharpProjects\Chapter2; // declared previously as a bool count = newValue;

@ placed before a string literal signals that the characters inside the double quotation marks should be interpreted verbatim
C# Programming: From Problem Analysis to Program Design 46

Examples of Assignment Statements (continued)

Figure 3-5 Impact of assignment statement

C# Programming: From Problem Analysis to Program Design 47

Arithmetic Operations
Simplest form of an assignment statement
resultVariable = operand1 operator operand2;

Space before and after every operator

C# Programming: From Problem Analysis to Program Design


+ Operator on a StringConcatenation

C# Programming: From Problem Analysis to Program Design


Fundamental Precedence Order of operators

Precedence order from high to low
() - elements within parentheses *, /, % - multiplicative +, - additive

Computation proceeds from left to right (left associative) within each precedence category

C# Programming: From Problem Analysis to Program Design


Basic Arithmetic Operations (continued)

Increment and Decrement Operations
Unary operator num++; // num = num + 1; --value1; // value = value 1; Preincrement/predecrement versus post int num = 30; System.Console.WriteLine(num++); // Displays 30 System.Console.WriteLine(num); // Display 31 System.Console.WriteLine(--num); // Displays 30
C# Programming: From Problem Analysis to Program Design 51

Compound Operations

C# Programming: From Problem Analysis to Program Design


Order of Operations

Parentheses () above *, / and % in precedence Associativity of operators

Left Right
C# Programming: From Problem Analysis to Program Design 53

Mixed Expressions
Implicit type coercion
Changes int data type into a double No implicit conversion from double to int

Figure 3-12 Syntax error generated for assigning a double to an int

C# Programming: From Problem Analysis to Program Design


Mixed Expressions (continued)

Explicit type coercion
Cast (type) expression examAverage = (exam1 + exam2 + exam3) / (double) count;
int value1 = 0, anotherNumber = 75; double value2 = 100.99, anotherDouble = 100; value1 = (int) value2; // value1 = 100 value2 = (double) anotherNumber; // value2 = 75.0

C# Programming: From Problem Analysis to Program Design


Formatting Output
You can format data by adding dollar signs, percent symbols, and/or commas to separate digits You can suppress leading zeros You can pad a value with special characters
Place characters to the left or right of the significant digits

Use format specifiers

C# Programming: From Problem Analysis to Program Design


Numeric Format Specifiers

C# Programming: From Problem Analysis to Program Design


Custom Numeric Format Specifiers

C# Programming: From Problem Analysis to Program Design


Custom Numeric Format Specifiers


C# Programming: From Problem Analysis to Program Design


Formatting Output

C# Programming: From Problem Analysis to Program Design


What is an Expression?
The most basic expression consists of an operator, two operands and an assignment. The following is an example of an expression: int theResult = 1 + 2; In the above example the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to an integer variable namedtheResult. The operands could just have easily been variables or constants (or a mixture of each) instead of the actual numerical values used in the example. In the remainder of this chapter we will look at the various types of operators available in C#.

The Basic Assignment Operator

We have already looked at the most basic of assignment operators, the = operator. This assignment operator simply assigns the result of an expression to a variable. In essence the = assignment operator takes two operands. The left hand operand is the variable to which a value is to be assigned and the right hand operand is the value to be assigned. The right hand operand is, more often than not, an expression which performs some type of arithmetic or logical evaluation. The following examples are all valid uses of the assignment operator: x = 10; // Assigns the value 10 to a variable named x x = y + z; // Assigns the result of variable y added to variable z to variable x x = y; // Assigns the value of variable y to variable x Assignment operators may also be chained to assign the same value to multiple variables. For example, the following code example assigns the value 20 to the x, y and z variables: int x, y, z; x = y = z = 20;

C# Arithmetic Operators
C# provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands. The exception is the unary negative operator (-) which serves to indicate that a value is negative rather than positive. This contrasts with the subtraction operator (-) which takes two operands (i.e. one value to be subtracted from another). For example: int x = -10; // Unary - operator used to assign -10 to a variable named x x = y - z; // Subtraction operator. Subtracts z from y

Note that multiple operators may be used in a single expression. For example: x = y * 10 + z - 5 / 4; Whilst the above code is perfectly valid it is important to be aware that C# does not evaluate the expression from left to right or right to left, but rather in an order specified by the precedence of the various operators. Operator precedence is an important topic to understand since it impacts the result of a calculation and will be covered in detail the next section.

C# Operator Precedence
When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression: 10 + 20 * 10 = 300 This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask C# to perform the same calculation and you get a very different answer: int x; x = 10 + 20 * 10; System.Console.WriteLine (x) The above code, when compiled and executed, will output the result 210. This is a direct result of operator precedence. C# has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, C# considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator. Fortunately the precedence built into C# can be overridden by surrounding the lower priority section of an expression with parentheses. For example: int x; x = (10 + 20) * 10; System.Console.WriteLine (x) In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication resulting in a value of 300. The following table outlines the C# operator precedence order from highest precedence to lowest:

Compound Assignment Operators

C# provides a number of operators designed to combine an assignment with a mathematical or logical operation. These are primarily of use when performing an evaluation where the result is to be stored in one of the operands. For example, one might write an expression as follows: x = x + y; The above expression adds the value contained in variable x to the value contained in variable y and stores the result in variable x. This can be simplified using the addition compound assignment operator: x += y The above expression performs exactly the same task as x = x + y but saves the programmer some typing.

Comparison Operators

n addition to mathematical and assignment operators, C# also includes set of logical operators useful for performing comparisons. These operators all return a Boolean (bool) true or false result depending on the result of the comparison. These operators are binary in that they work with two operands. Comparison operators are most frequently used in constructing program flow control. For example an if statement may be constructed based on whether one value matches another: if (x == y) System.Console.WriteLine ("x is equal to y"); The result of a comparison may also be stored in a bool variable. For example, the following code will result in a true value being stored in the variable result: bool result; int x = 10; int y = 20; result = x < y;

Boolean Logical Operators

Another set of operators which return boolean true and false values are the C# boolean logical operators. These operators both return boolean results and take boolean values as operands. The key operators are NOT (!), AND (&&), OR (||) and XOR (^). The NOT (!) operator simply inverts the current value of a boolean variable, or the result of an expression. For example, if a variable named flag is currently true, prefixing the variable with a '!' character will invert the value to be false: bool flag = true; //variable is true bool secondFlag; secondFlag = !flag; // secondFlag set to false The OR (||) operator returns true if one of its two operands evaluates to true, otherwise it returns false. For example, the following example evaluates to true because at least one of the expressions either side of the OR operator is true: if ((10 < 20) || (20 < 10)) System.Console.WriteLine("Expression is true"); The AND (&&) operator returns true only if both operands evaluate to be true. The following example will return false because only one of the two operand expressions evaluates to true: if ((10 < 20) && (20 < 10)) System.Console.WriteLine("Expression is true"); The XOR (^) operator returns true if one and only one of the two operands evaluates to true. For example, the following example will return true since only one operator evaluates to be true: if ((10 < 20) ^ (20 < 10)) System.Console.WriteLine("Expression is true"); If both operands evaluated to be true, or both were false the expression with return false.

The Ternary Operator

C# uses something called a ternary operator to provide a shortcut way of making decisions. The syntax of the ternary operator is as follows: [condition] ? [true expression] : [false expression] The way this works is that [condition] is replaced with an expression that will return either true or false. If the result is true then the expression that replaces the [true expression] is evaluated. Conversely, if the result was false then the [false expression] is evaluated. Let's see this in action: int x = 10; int y = 20; System.Console.WriteLine( x > y ? x : y );

IF Loop
The if statement is perhaps the most basic of flow control options available to the C# programmer. Programmers who are familiar with C, C++ or Java will immediately be comfortable using C# if statements. The basic syntax of C# if statement is as follows: if (boolean expression) { // C# code to be performed when expression evaluates to true here }

int x = 10; if ( x > 9 ) { System.Console.WriteLine ("x is greater than 9!"); }

Using if ... else .. Statements

if (boolean expression) { // Code to be executed if expression is true } else { // Code to be executed if expression is false }

int x = 10; if ( x > 9 ) { System.Console.WriteLine ("x is greater than 9!"); } else { System.Console.WriteLine ("x is less than 9!"); }

Using if ... else if .. Statements

int x = 9; if (x == 10) { System.Console.WriteLine ("x is 10"); } else if (x == 9) { System.Console.WriteLine ("x is 9"); } else if (x == 8) { System.Console.WriteLine ("x is 8"); }

Using the switch Statement Syntax

switch (value) { case constant: statements break/jump case constant: statements break/jump default: statements break/jump }

A switch Statement Example

using System; using System.Text; class Hello { static void Main() { string carModel; string carManufacturer; System.Console.Write ("Please Enter Your Vehicle Model: "); carModel = System.Console.ReadLine(); switch (carModel) { case "Patriot": case "Liberty": case "Wrangler": carManufacturer = "Jeep"; break; case "Focus": carManufacturer = "Ford"; break; case "Corolla": carManufacturer = "Toyota"; break; default: carManufacturer = "unknown"; break; } System.Console.Write("Manufacturer is " + carManufacturer); }}

For loop
int j = 10; for (int i=0; i<100; i++) { j += j; } System.Console.WriteLine ("j = " + j);

foreach Statement
Iteration of arrays
public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s); }

Iteration of user-defined collections

foreach (Customer c in customers.OrderBy("name")) { if (c.Orders.Count != 0) { ... } }

while Loop
while (''condition'') { // C# statements go here }

int myCount = 0; while ( myCount < 100 ) { myCount++; }

do ... while loops

do { // C# statements here } while (''conditional expression'')

int i = 10; do { i--; } while (i > 0)

Parameter Arrays
Can write printf style methods
Type-safe, unlike C++
void printf(string fmt, params object[] args) { foreach (object x in args) { ... } } printf("%s %i %i", str, int1, int2); object[] args = new object[3]; args[0] = str; args[1] = int1; Args[2] = int2; printf("%s %i %i", args);

Rectangular Arrays
This is the arrays datatype, most of us are familiar with. Rectangular arrays may be may be singledimensional or multi-dimensional. Declaring single dimenisonal arrays. short[] shtEmpNo; int[] intSalary; Declaring single dimenisonal arrays. short[] shtEmpNo; int[] intSalary; Declaring multi-dimenisonal arrays. // two-dimensional arrays of short short[,] shtEmpNo; // three-dimensional arrays of int int[,,] intSalary; Rule: Element-type (int, short, long) Rank-specifiers ([], [,,]) Name (Arrays Name) Array types are reference types, and so the declaration of an array variable merely sets aside space for the reference to the array. Array instances are actually created via array initializers and array creation expressions

Intialising Arrays // 5 member single-dimensional arrays intialised short[] shtEmpNo = new short[5]; // 3 member single-dimensional arrays int[] intSlNo = new int[] {1, 2, 3}; // 3*2 member two-dimensional arrays int[,] intCount = new int[,] {{1, 2, 3}, {4, 5, 6}}; // 1*3 member three-dimesional arrays. int[,,] intDec = new int[10, 20, 30];

Jagged Arrays
Jagged arrrays are nothing but arrays of arrays. This is very clear from the 'Declaration' sysnatx. See the [] appears more than once in the following declaration. Declaring Jagged Arrays // "jagged" array: array of (array of int) int[][] j2; // array of (array of (array of int)) int[][][] j3; Rectangualr Arrays ~ Jagged Arrays

//single-dimensional rectangukar arrays int[] r1 = new int[] {1, 2, 3}; //two-dimensional rectangualar arrays int[,] r2 = new int[,] {{1, 2, 3}, {4, 5, 6}}; //three-dimesional rectangular arrays int[,,] r3 = new int[10, 20, 30]; //"jagged" array: araay of(array of int) int[][] j2 = new int[3][]; j2[0] = new int[] {1, 2, 3}; j2[1] = new int[] {1, 2, 3, 4, 5, 6}; j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};

Structures are basically value types. They are defined by using the struct keyword. You can access the variables inside a structure by creating an object of the structure. The only difference is that you don't have to use the syntax for creating an object from a class for structures. Listing 1 explains this concept clearly.

using System; enum Employees:byte { ok = 50,cancel = 100 } struct Emp { public Employees EM; public string id; } class Emptest { public static void Main() { Emp E; E.EM = Employees.cancel; = "002"; Console.WriteLine(E.EM); Console.WriteLine(; } }

Enumerations are a set of names for the corresponding numerical values. enum Employees { OK; // CANCEL; }

using System; enum Employees { Instructors, Assistants, Counsellors } class Employeesenum { public static void Display(Employees e) { switch(e) { case Employees.Instructors: Console.WriteLine("You are an Instructor"); break;

case Employees.Assistants: Console.WriteLine("You are one of the Assistants"); break; case Employees.Counsellors: Console.WriteLine("You are a counsellor"); break; default:break; } } public static void Main(String[] args) { Employees emp; emp = Employees.Counsellors; Display(emp); } }

REFERENCES Lecture notes on c#