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

Similar documents
Industrial Programming

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

Introduction to Programming Using Java (98-388)

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

DigiPen Institute of Technology

12 CREATING NEW TYPES

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

Introduction to C# Applications

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

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

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

Visual C# Instructor s Manual Table of Contents

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

.Net Technologies. Components of.net Framework

Francesco Nidito. Programmazione Avanzata AA 2007/08

Chapter 2: Using Data

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

Industrial Programming

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

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

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

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

A Comparison of Visual Basic.NET and C#

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

Input And Output of C++

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

Introduction to C++ with content from

Chapter 1 Getting Started

Programming in Haskell Aug-Nov 2015

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

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

Programming in C UVic SEng 265

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

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

CSC Java Programming, Fall Java Data Types and Control Constructs

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

Understand Computer Storage and Data Types

Tokens, Expressions and Control Structures

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

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

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

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

Object-Oriented Programming in C# (VS 2015)

DAD Lab. 1 Introduc7on to C#

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

EMBEDDED SYSTEMS PROGRAMMING Language Basics

Lecture 12: Data Types (and Some Leftover ML)

Type Conversion. and. Statements

1.3b Type Conversion

Chapter-8 DATA TYPES. Introduction. Variable:

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Introduction To C#.NET

EEE-425 Programming Languages (2013) 1

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

COP4020 Programming Assignment 1 - Spring 2011

Short Notes of CS201

C# Language Specification

Object-Oriented Programming in C# (VS 2012)

Instantiation of Template class

CS201 - Introduction to Programming Glossary By

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Chapter 7: Structuring the Data. Lecture7 1

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points.

BASIC ELEMENTS OF A COMPUTER PROGRAM

C++ Important Questions with Answers

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

Question And Answer.


CS201- Introduction to Programming Current Quizzes

Pace University. Fundamental Concepts of CS121 1

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

BLM2031 Structured Programming. Zeyneb KURT

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

CSCI 1061U Programming Workshop 2. C++ Basics

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

Type Checking. Prof. James L. Frankel Harvard University

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

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Basic Elements of C. Staff Incharge: S.Sasirekha

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

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

Programming refresher and intro to C programming

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

The Warhol Language Reference Manual

High Performance Computing in C and C++

CPSC 3740 Programming Languages University of Lethbridge. Data Types

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

PROGRAMMING FUNDAMENTALS

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

COMP 2355 Introduction to Systems Programming

CSCE 314 Programming Languages

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Primer 1: Types, Classes and Operators

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Lecture 3. The syntax for accessing a struct member is

Transcription:

C# Types Industrial Programming Lecture 3: C# Fundamentals Industrial Programming 1 Industrial Programming 2 Value Types Memory location contains the data. Integers: Signed: sbyte, int, short, long Unsigned: byte, uint, ushort, ulong e.g. int count = 5; Floating points: float, double Examples double average = 10.5; float total = 34.88f; Signed and Unsigned By default int, short, long are signed data types as they can hold a negative of a positive value of their ranges. Unsigned variable can only hold positive values of its range. Industrial Programming 3 Industrial Programming 4

Types and Values Value Types (cont'd) Decimal types: appropriate for storing monetary data. Provides greater precision. decimal profit = 2211655.76M; Boolean variables: true or false. bool student = true; Industrial Programming 5 Industrial Programming 6 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. Value Types (cont'd) The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1, eg enum Days Sat, Sun, Mon, Tue, Wed, Thu, Fri; In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initialisers to override the default values, eg 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. Industrial Programming 7 Industrial Programming 8

Value Types (cont'd) Example of enum types: enum Fruit apple, banana, peach Fruit f = Fruit.apple Value Types (cont'd) Struct types: User-defined types. Can contain data members of different types. Can t be extended. struct Person public String fname, lname; public Person(String fname, String lname) this.fname = fname; this.lname = lname; Person p = new Person( John, Smith ); Industrial Programming 9 Industrial Programming 10 Classes Reference type Structs vs Classes 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 inheritance Can implement one or more interfaces Cannot initialize fields with initializers Cannot have a parameterless constructor Industrial Programming 12 Reference Types A variable of reference type contains a reference to a memory location where data is stored (as pointers in C/C++). Direct inheritance from Object. Can implement many interfaces. Two predefined reference types in C#: String and Object. E.g. string name = John ; Object, root of all types. Industrial Programming 13

Value vs Reference Type 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. 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). int n = 5; object nobject = n; //boxing int n2 = (int) nobject; //unboxing Industrial Programming 14 Industrial Programming 15 Casting There are 2 ways of changing the type of a value in the program Implicit conversion by assignment e.g. short myshort = 5; int myint = myshort; Explicit conversion using the syntax (type)expression double mydouble = 4.7; int myint = (int)mydouble; Industrial Programming 16 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 Industrial Programming 17

Arrays C# supports one- and multi-dimensional arrays. One-dimensional array Declaring: string[] names = new string[30]; Starts at index 0 up to index 29. Accessing: names[2] = john ; Multi-dimensional array int[,] numbers = new int[5,10]; Industrial Programming 18 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 Industrial Programming 19 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]; Industrial Programming 20 Decision Making The if : If (expression) 1 [else 2] The expression must evaluate to bool. If expression is true, flow of control is passed to 1, otherwise, control is passed to 2. Can have multiple else clauses (using else if). Industrial Programming 21

Logical Operators For comparing values these operators exist: ==,!=, <=, >=, <, > NB: = is for assignment, not 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 Industrial Programming 22 Decision Making (cont'd) The switch. switch (switch_expression) case constant-expression: jump.. case constant-expressionn: N jump [default] Industrial Programming 23 Decision Making (cont'd) Iteration Switch_expression must be of type sbyte, byte, short, ushort, int, uint, long, ulong, char or string. Each case clause must include a jump- (e.g. break ) apart from the last case in the switch. Case clauses can be combined by writing them directly one after the other. The switch_expression is evaluated and compared to each of the constant-expressions. On finding a match, control is passed to the first line of code in the matching case. If no match is found, control is passed to the default clause. Industrial Programming 24 The while : boolean expression is evaluated before the is executed, which is iterated while the boolean expression remains true. while (boolean_expression) The do/while : boolean expression is evaluated after the is executed, which is iterated. do while (boolean_expression) Industrial Programming 25

Iteration (cont'd) The for for (initialization; boolean_expression; step) The foreach Specifically designed for the iteration over arrays and collections. foreach (type identifier in expression) 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. static int Get (int[] arr, int n) return arr[n]; This static method is called directly, e.g. i = Get(myArr, 3); Exercise: check that n is in a valid range Industrial Programming 26 Industrial Programming 27 Function Parameters Example: nullable types All objects, arrays and strings are passed by reference, i.e. changes effect the argument that is passed to the function: static void Set (int[] arr, int n, int x) arr[n] = x; But, value types are copied. The keyword ref is needed for passing by reference: static void SetStep (int[] arr, ref int n, int x) arr[n] = x; n += 1 ; Industrial Programming 28 public static int? Min(int[] sequence) int theminimum; if (sequence.length == 0) return null; else theminimum = sequence[0]; foreach(int e in sequence) if (e < theminimum) theminimum = e; return theminimum; Industrial Programming 29

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 use 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 Is min, if its value is non-null, 0 otherwise. Industrial Programming 30 Example: nullable types (cont'd) public static void ReportMinMax(int[] sequence) if (Min(sequence).HasValue && Max(sequence).HasValue) Console.WriteLine("Min: 0. Max: 1", Min(sequence), Max(sequence)); else Console.WriteLine("Int sequence is empty"); public static void Main() int[] is1 = new int[] -5, -1, 7, -8, 13; int[] is2 = new int[] ; ReportMinMax(is1); ReportMinMax(is2); Industrial Programming 31 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) Industrial Programming 33 Exercise (cont'd) (a) Use the SetStep method to implement a method Set0, which sets all array elements to the value 0. (b) Implement a method, reading via ReadLine, and counting how many unsigned short, unsigned int and unsigned long values have been read. (c) Define complex numbers using structs, and implement basic arithmetic on them. (d) Implement Euclid's greatest common divisor algorithm as a static method over 2 int parameters. (e) Implement matrix multiplication as a static method taking 2 2-dimensional arrays as arguments. Industrial Programming 34