C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Similar documents
Industrial Programming

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

Introduction to Programming Using Java (98-388)

DigiPen Institute of Technology

Introduction to C# Applications

Introduce C# as Object Oriented programming language. Explain, tokens,

C# Data Manipulation

C# and Java. C# and Java are both modern object-oriented languages

C# Data Manipulation

Chapter 2: Using Data

12 CREATING NEW TYPES

A case study of delegates and generics in C#

Motivation. Reflection in C# Case study: Implicit Serialisation. Using implicit serialisation. Hans-Wolfgang Loidl

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Visual C# Instructor s Manual Table of Contents

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Introduction To C#.NET

Where we are Distributed and Parallel Technology. Union Types. A Tree Structure. t tag node. C Revision (Part II)

C#: framework overview and in-the-small features

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

.Net Technologies. Components of.net Framework

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Chapter 1 Getting Started

Introduction to C++ with content from

C++ (Non for C Programmer) (BT307) 40 Hours

Input And Output of C++

Francesco Nidito. Programmazione Avanzata AA 2007/08

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Programming in C. What is C?... What is C?

C# Fundamentals. built in data types. built in data types. C# is a strongly typed language

A Comparison of Visual Basic.NET and C#

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Programming in Haskell Aug-Nov 2015

Computer Science II (20082) Week 1: Review and Inheritance

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Pace University. Fundamental Concepts of CS121 1

Chapter-8 DATA TYPES. Introduction. Variable:

BASIC ELEMENTS OF A COMPUTER PROGRAM

Chapter 6 part 1. Data Types. (updated based on 11th edition) ISBN

Object-Oriented Programming in C# (VS 2015)

Computing is about Data Processing (or "number crunching") Object Oriented Programming is about Cooperating Objects

CSC Java Programming, Fall Java Data Types and Control Constructs

CS2141 Software Development using C/C++ C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics

Lecture 12: Data Types (and Some Leftover ML)

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

Tokens, Expressions and Control Structures

Understand Computer Storage and Data Types

EEE-425 Programming Languages (2013) 1

Computer Science II (20073) Week 1: Review and Inheritance

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

Introduction. Primitive Data Types: Integer. Primitive Data Types. ICOM 4036 Programming Languages

Object-Oriented Programming in C# (VS 2012)

BLM2031 Structured Programming. Zeyneb KURT

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

C++ Important Questions with Answers

1.3b Type Conversion

Type Conversion. and. Statements

Question And Answer.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Enumerated Types. Mr. Dave Clausen La Cañada High School

DAD Lab. 1 Introduc7on to C#

CS313D: ADVANCED PROGRAMMING LANGUAGE

Short Notes of CS201

C# Language Specification

Java is an objet-oriented programming language providing features that support

F28HS Hardware-Software Interface: Systems Programming

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

CS201 - Introduction to Programming Glossary By

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

PROGRAMMING FUNDAMENTALS

A Fast Review of C Essentials Part I

EMBEDDED SYSTEMS PROGRAMMING Language Basics

High Performance Computing in C and C++

Basic Elements of C. Staff Incharge: S.Sasirekha

The Warhol Language Reference Manual

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Creating a C++ Program

COP4020 Programming Assignment 1 - Spring 2011

Programming refresher and intro to C programming

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CSCE 314 Programming Languages

CPSC 3740 Programming Languages University of Lethbridge. Data Types

Code Contracts in C#

Lesson 02 Working with Data Types. MIT 31043: VISUAL PROGRAMMING By: S. Sabraz Nawaz Senior Lecturer in MIT

Instantiation of Template class

C# Threading. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Chapter 7: Structuring the Data. Lecture7 1

2. C99 standard guarantees uniqueness of characters for internal names. A. 12 B. 26 C. 31 D. 48

Transcription:

C# Fundamentals Hans-Wolfgang Loidl <H.W.Loidl@hw.ac.uk> School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2018/19 H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 1 / 28

C# Types H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 2 / 28

Value Types Variables stand for the value of that type ( has value ) Integers: Signed: sbyte, int, short, long Unsigned: byte, uint, ushort, ulong Floating point: float double Examples: double average = 10.5 float total = 34.87f H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 3 / 28

Signed vs Unsigned By default int, short, long are signed data types as they can hold a negative or a positive value of their ranges. Unsigned variables can only hold positive values of its range. Other value types: Decimal types: appropriate for storing monetary data. Provides greater precision. decimal profit = 2211655.76M; Boolean variables: True or False. bool student = True; H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 4 / 28

Signed vs Unsigned By default int, short, long are signed data types as they can hold a negative or a positive value of their ranges. Unsigned variables can only hold positive values of its range. Other value types: Decimal types: appropriate for storing monetary data. Provides greater precision. decimal profit = 2211655.76M; Boolean variables: True or False. bool student = True; H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 4 / 28

Types and Values H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 5 / 28

Value Types (cont d) Enum Types: The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. Example: enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri}; The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, the next 1, etc. In the above example, Sat is 0, Sun is 1 etc Enumerators can have initialisers to override the default values, e.g. enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; In this enumeration, the sequence of elements is forced to start from 1 instead of 0. H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 6 / 28

Value Types (cont d) Enum Types: The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. Example: enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri}; The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, the next 1, etc. In the above example, Sat is 0, Sun is 1 etc Enumerators can have initialisers to override the default values, e.g. enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; In this enumeration, the sequence of elements is forced to start from 1 instead of 0. H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 6 / 28

Value Types (cont d) Enum Types: The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. Example: enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri}; The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, the next 1, etc. In the above example, Sat is 0, Sun is 1 etc Enumerators can have initialisers to override the default values, e.g. enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; In this enumeration, the sequence of elements is forced to start from 1 instead of 0. H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 6 / 28

Struct Types Struct types: are user-defined types can contain data members of different types cannot be extended Example: 1 struct Person { 2 public String fname, lname ; 3 public Person ( String fname, String lname ) { 4 this. fname = fname ; 5 this. lname = lname ; 6 } 7 } 8 Person p = new Person (" John ", " Smith "); H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 7 / 28

Struct Types Struct types: are user-defined types can contain data members of different types cannot be extended Example: 1 struct Person { 2 public String fname, lname ; 3 public Person ( String fname, String lname ) { 4 this. fname = fname ; 5 this. lname = lname ; 6 } 7 } 8 Person p = new Person (" John ", " Smith "); H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 7 / 28

Structs vs Classes Classes Reference type Used w/ dynamic instantiation Ancestors of class Object Can be extended by inheritance Can implement one or more interfaces Can initialize fields with initializers Can have a parameterless constructor Structs Value type Used with static instantiation Ancestors of class Object Cannot be extended by inhe Can implement one or more Cannot initialize fields with i Cannot have a parameterless H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 8 / 28

Reference Types A variable of reference type contains a reference to a memory location where data is stored (as pointers in C/C++) ( contains value ). Properties: Direct inheritance from Object. Can implement many interfaces. Two predefined reference types in C#: String, e.g.: string name = "John"; Object, root of all types H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 9 / 28

Value vs Reference Types If x and y are of value type, the assignment x = y copies the contents of y into x. If x and y are of reference type, the assignment x = y causes x to point to the same memory location as y. Example: 1 Person p = new Person (" John ", " Smith "); 2 Person q = p; 3 p. fname = " Will "; 4 // what is the value of q. fname? H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 10 / 28

Value vs Reference Types If x and y are of value type, the assignment x = y copies the contents of y into x. If x and y are of reference type, the assignment x = y causes x to point to the same memory location as y. Example: 1 Person p = new Person (" John ", " Smith "); 2 Person q = p; 3 p. fname = " Will "; 4 // what is the value of q. fname? H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 10 / 28

Boxing and Unboxing Boxing is the conversion of a value type to a reference type. Unboxing is the opposite process. Using boxing, an int value can be converted to an object to be passed to a method (that takes an object as argument). Example: 1 int n = 5; 2 object nobject = n; // boxing 3 int n2 = ( int ) nobject ; // unboxing H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 11 / 28

Boxing and Unboxing Boxing is the conversion of a value type to a reference type. Unboxing is the opposite process. Using boxing, an int value can be converted to an object to be passed to a method (that takes an object as argument). Example: 1 int n = 5; 2 object nobject = n; // boxing 3 int n2 = ( int ) nobject ; // unboxing H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 11 / 28

Casting There are 2 ways of changing the type of a value in the program Implicit conversion by assignment e.g. 1 short myshort = 5; 2 int myint = myshort ; Explicit conversion using the syntax (type)expression 1 double mydouble = 4. 7; 2 int myint = ( int ) mydouble ; H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 12 / 28

Nullable types Variables of reference type can have the value null, if they don t refer to anything. Variables of value type cannot have the value null, because they represent values. Sometimes it is useful to have a variable of value type that may have no value. To this end, a nullable type can be used: int? i; Here, i is of type int, but may have the value null H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 13 / 28

Arrays C# supports one- and multi-dimensional arrays. One-dimensional array are declared like this string[] names = new string[30]; starts at index 0 up to index 29 (in general, bound - 1). are accessed like this: names[2] = "John"; Multi-dimensional array: int[,] numbers = new int[5,10]; H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 14 / 28

Some useful methods on arrays Length... Gives the number of elements in an array. Rank... Gives the number of dimensions of the array. GetLength(n)... Gives the number of elements in the n-th dimension H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 15 / 28

Jagged Arrays A jagged array is a multi-dimensional array, where the rows may have different sizes. It is declared like this int [][] myjaggedarray = new int[4][]; The rows are filled in separately myjaggedarray[0] = new int[5]; Access to array elements works like this: myjaggedarray[0][2]; H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 16 / 28

Control Structures: Conditional 1 if ( expression ) 2 statement 1 3 [ else 4 statement 2] In the above if statement: The expression must evaluate to a bool value. If expression is true, flow of control is passed to statement 1 otherwise, control is passed to statement 2. Can have multiple else clauses (using else if). H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 17 / 28

Logical Operators For comparing values these operators exist: ==,!=, <=, >=, <, > NB: = is for assignment; == is for equality test These operators combine boolean values: &&,,! Operators over int and float: +, -, *, / (% int only) A conditional expression is written like this: boolean_expr? expr_true : expr_false H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 18 / 28

Control Structures: Switch 1 switch ( switch_ expression ) { 2 case constant - expression : 3 statement 4 jump statement 5... 6 case constant - expressionn : 7 statementn 8 jump statement 9 [ default ] 10 } switch_expression must be of type sbyte, byte, short, ushort, int, uint, long, ulong, char or string. Each case clause must include a jump-statement (e.g. break statement) apart from the last case in the switch. Case clauses can be combined by writing them directly one after the other. H-W. Loidl The(Heriot-Watt switch_expression Univ) F20SC/F21SC is evaluated 2018/19 and compared C# Fundamentalsto 19 / 28

Control Structures: Iteration 1 while ( boolean_ expression ) 2 statement In a while statement, the boolean_expression is evaluated before the statement is executed, which is iterated while the boolean_expression remains true. 1 do 2 statement 3 while ( boolean_ expression ) In a do/while statement the boolean_expression is evaluated after the statement is executed, which is iterated until the boolean_expression becomes false. H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 20 / 28

Control Structures: Iteration 1 while ( boolean_ expression ) 2 statement In a while statement, the boolean_expression is evaluated before the statement is executed, which is iterated while the boolean_expression remains true. 1 do 2 statement 3 while ( boolean_ expression ) In a do/while statement the boolean_expression is evaluated after the statement is executed, which is iterated until the boolean_expression becomes false. H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 20 / 28

Control Structures: Iteration (cont d) 1 for ( initialization ; boolean_ expression ; step ) 2 statement The for statement performs initialization before the first iteration iterates while boolean_expression remains true performs step at the end of each iteration 1 foreach ( type identifier in expression ) 2 statement The foreach statement iterates over arrays and collections. The variable identifier is bound to each element in turn. H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 21 / 28

Control Structures: Iteration (cont d) 1 for ( initialization ; boolean_ expression ; step ) 2 statement The for statement performs initialization before the first iteration iterates while boolean_expression remains true performs step at the end of each iteration 1 foreach ( type identifier in expression ) 2 statement The foreach statement iterates over arrays and collections. The variable identifier is bound to each element in turn. H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 21 / 28

Functions Functions (or static methods) encapsulate common sequences of instructions. As an example, this function returns the n-th element of an array, e.g. 1 static int Get ( int [] arr, int n) { 2 return arr [n]; 3 } This static method is called directly, e.g. 1 i = Get ( myarr, 3); Exercise: check that n is in a valid range H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 22 / 28

Function Parameters All objects, arrays and strings are passed by reference, i.e. changes effect the argument that is passed to the function: 1 static void Set ( int [] arr, int n, int x) { 2 arr [n] = x; 3 } But, value types are copied. The keyword ref is needed for passing by reference: 1 static void SetStep ( int [] arr, ref int n, int x) { 2 arr [n] = x; 3 n += 1 ; 4 } H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 23 / 28

Example: nullable types 1 public static int? Min ( int [] sequence ){ 2 int theminimum ; 3 if ( sequence. Length == 0) 4 return null ; 5 else { 6 theminimum = sequence [ 0]; 7 foreach ( int e in sequence ) 8 if ( e < theminimum ) 9 theminimum = e; 10 } 11 return theminimum ; 12 } H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 24 / 28

Discussion The type int? is a nullable int type. The value null of this type is used to indicate that there is no minimum in the case of an empty sequence. The method HasValue can be used to check whether the result is null: int? min = Min(seq); if (min.hasvalue)... The combinator?? can be used to select the first non-null value: min?? 0 This returns the value of min, if its value is non-null, 0 otherwise. H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 25 / 28

Example: nullable types (cont d) 1 public static void ReportMinMax ( int [] sequence ) { 2 if ( Min ( sequence ). HasValue && Max ( sequence ). HasValue ) 3 Console. WriteLine (" Min : {0}. Max : {1} ", 4 Min ( sequence ), Max ( sequence )); 5 else 6 Console. WriteLine (" Int sequence is empty "); 7 } 8 9 public static void Main (){ 10 int [] is1 = new int [] { -5, -1, 7, -8, 13}; 11 int [] is2 = new int [] { }; 12 ReportMinMax ( is1 ); 13 ReportMinMax ( is2 ); 14 } H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 26 / 28

Exercises Recommended Exercises: (a) Define Weekday as an enumeration type and implement a NextDay method (b) Implement a WhatDay method returning either WorkDay or WeekEnd (use another enum) (c) Write a method calculating the sum from 1 to n, for a fixed integer value n (d) Write a method calculating the sum over an array (one version with foreach, one version with explicit indexing) H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 27 / 28

Exercises (cont d) (e) Use the SetStep method to implement a method Set0, which sets all array elements to the value 0. (f) Implement a method, reading via ReadLine, and counting how many unsigned short, unsigned int and unsigned long values have been read. (g) Define complex numbers using structs, and implement basic arithmetic on them. Mandatory exercises: (I) Implement Euclid s greatest common divisor algorithm as a static method over 2 int parameters. (II) Implement matrix multiplication as a static method taking two 2-dimensional arrays as arguments. H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19 C# Fundamentals 28 / 28