C# programming for .NET Frameworkmcsc.sc.mahidol.ac.th/courses/csharp/slides/csharp.pdf · 1. Common Language Runtime (CLR) manages program execution at run time •memory management

Post on 31-Jan-2020

7 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

C# Programming for.NET Framework

Chaiwoot Boonyasiriwat

December 1, 2018

.NET Framework

In 1990s, Windows programming technology had diverged into• Raw Win32 API• Microsoft Foundation Classes (MFC)• Component Object Model (COM)

These were aimed for desktop, not web Programming language: C, C++, Visual Basic

Before .NET

Solis and Schrotenboer (2018)

.NET Framework (released in 2002) features• Multiple platforms: system can run on

desktops, servers, mobile phones, web• Industry standards: system uses industry-

standard protocols (XML, HTTP, SOAP, JSON)• Security: system provides safer execution

environment

Enter Microsoft .NET

Solis and Schrotenboer (2018)

1. Common Language Runtime (CLR) manages program execution at run time• memory management and garbage collection• code safety verification• code execution, thread management,

exception handling2. Programming tools: Visual Studio IDE,

compilers (C#, F#, VB), debuggers, ASP.NET3. Base Class Library (BCL)

.NET Framework Components

Solis and Schrotenboer (2018)

.NET Framework Components

Solis and Schrotenboer (2018)

Object-oriented development environment Automatic garbage collection Interoperability between .NET languages,

Win32 DLLs, and COM Simplified deployment: no registry needed Type safety checked by CLR Base Class Library (BCL): general base classes,

collection classes, threading and synchronization classes, XML classes

Programming Environment

Solis and Schrotenboer (2018)

Source code is compiled into assembly Assembly is in intermediate language called CIL,

not native machine code Assembly is either executable (.exe) or DLL (.dll) Assembly contains• CIL of the program• metadata about types used in the program• metadata about references to other

assemblies

Common Intermediate Language

Solis and Schrotenboer (2018)

Common Intermediate Language

Solis and Schrotenboer (2018)

CIL is compiled into native machine code at run time and CLR performs the following steps. Check assembly's security characteristics Allocate space in memory Send assembly's executable CIL code to

just-in-time (JIT) compiler which compiles only needed portion of assembly to native code

Native Code and Execution

Solis and Schrotenboer (2018)

Native Code and ExecutionSolis and Schrotenboer (2018)

Compilation and Execution

Solis and Schrotenboer (2018)

Common Language Runtime

Solis and Schrotenboer (2018)

Common Language Infrastructure

"CLI is a set of specifications that lays out the architecture, rules, conventions of the system."

Solis and Schrotenboer (2018)

Important Parts of CLI Common Type System (CTS)• CTS defines a set of intrinsic types• Types provided .NET languages map to

subset of the defined intrinsic types• All types are derived from a common base

class called object Common Language Specification (CLS)• CLS specifies rules, properties, behaviors of

.NET programming language, e.g., data types, class construction, parameter passing

Solis and Schrotenboer (2018)

.NET is a platform for building applications. .NET Framework: for websites, services,

desktop apps on Windows only .NET Core: for websites, servers, and console

apps on Windows, Linux, and macOS Xamarin/Mono: for mobile apps

.NET Standard: base set of APIs common to all .NET implementations

.NET Implementations

https://www.microsoft.com/net/learn/dotnet/what-is-dotnet

Web: web apps and services for Windows, Linux, macOS, and Docker

Mobile: single codebase to build native mobile apps for iOS, Android, and Windows

Desktop: desktop apps for Windows/macOS Gaming: games for desktops, phones, consoles Machine learning and AI algorithms in apps Internet of Things: IoT apps for Raspberry Pi

and microcontrollers

Application Models

https://www.microsoft.com/net/learn/dotnet/what-is-dotnet

C# can be used to create Windows client applications XML Web services Distributed components Client-Server applications Database applications

C# and .NET Framework

https://docs.microsoft.com/en-us/dotnet/csharp/getting-started/introduction-to-the-csharp-language-and-the-net-framework

Introduction to C#

C# is similar to C, C++, Java, JavaScript C# is object-oriented and component-oriented C# features include• garbage collection• delegates• lambda expressions• generic methods and types• XML documentation comments• Language-Integrated Query (LINQ)

C# Language

https://docs.microsoft.com/en-us/dotnet/csharp/getting-started/introduction-to-the-csharp-language-and-the-net-framework

File: hello.cs

using System;

class Hello {

static void Main() {

Console.WriteLine("Hello, World");

}

}

Command-line compilation: csc hello.cs

Hello World

https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/index

Programs declare types, which contain members and can be organized into namespace (a set of types)

Programs are compiled into assemblies with extension .exe (app) or .dll (library)

Assemblies contain executable code in Intermediate Language (IL) instructions.

IL code is converted into machine code by Just-In-Time (JIT) compiler of .NET CLR.

C# Program Structure

https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/program-structure

File: simplelib.csusing System;

namespace SimpleLib {

public class Lib {

float x, y;

public void print(string str) {

Console.WriteLine("Hello " +str);

}

}

}

Compilation: csc /t:library simplelib.cs

Library

File: app1.csusing System;

using SimpleLib;

class App {

static void Main() {

Lib c = new Lib();

c.print("Jack");

}

}

Compilation:csc /r:simplelib.dll app1.cs

Using Library in App

Identifiers are character strings used to name variables, methods, parameters, etc.

Identifiers are case-sensitive Rules for naming an identifier• alphabets and _ are allowed at any position• digits are not allowed in the first position• @ is only allowed in the first position

Identifiers

Solis and Schrotenboer (2018)

C# keywords cannot be used as identifier, e.g., variable name, unless prefaced with @

C# Keywords

Solis and Schrotenboer (2018)

Contextual keywords act as keywords only in certain language constructs.

In other parts of the code, contextual keywords can be used as identifier.

C# Contextual Keywords

Solis and Schrotenboer (2018)

General form of Console.Write() and Console.WriteLine():

Write(FormatString, val0, val1, ...)

Example:Console.Write("a={0},b={1}",1,"F");

String Interpolation (introduced in C# 6):int a = 10, b = -1;

Console.WriteLine($"a={a},b={b}");

Console.WriteLine($"a+b = {a+b}");

Text Output from Program

Solis and Schrotenboer (2018)

WriteLine("a={0} ",1); numberWriteLine("a={0:C} ",1); currencyint a = 1;

WriteLine($"a = {a:C}");

WriteLine($"|{0,+10}|",2); right alignmentWriteLine($"|{0,-10}|",2); left alignment

Formatting Numeric Strings

Solis and Schrotenboer (2018)

: colon must be next to format specifier without spaces format specifier is a single character from 9 characters

• C, c = currency, precision = # of decimal places• D, d = decimal, for integer only, precision = # of digits• E, e = scientific notation, precision = # of decimal places• F, f = fixed-point decimal, precision = # of decimal places• G, g = fixed-point or scientific notation depends on value• N, n = number with comma separator• P, p = percent, precision = # of decimal places• R, r = round-trip, Parse method will convert to original• X, x = hexadecimal, precision = # number of digits

precision specifier is optional and consists of 1 or 2 digits

3-Part Format Field

Solis and Schrotenboer (2018)

single-line comment: // commentint a; // angle

multiline or delimited comment:/*

* comment

*/

int a, /* b, */ c;

Comments

Solis and Schrotenboer (2018)

"Documentation comment contains XML text that can be used to produce program documentation."

/// <summary>

/// Hello World Program

/// </summary>

class Hello {

...

}

Documentation Comments

Solis and Schrotenboer (2018)

Types and Variables

"C# program or DLL is a set of type declarations." An executable must have one class type that includes a

method called Main. "namespace is a way of grouping a related set of type

declarations." "A type is a template for creating data structures." Simple types such as int, float can store only a single

data item. array can store multiple items of the same type.

Individual item of array is called element and is referenced by a number called index.

Type

Solis and Schrotenboer (2018)

Some types such as class and struct can contain multiple items of different types. Individual item of these types is called member which has a distinct name.

2 kinds of members• data member• function member

Type

Solis and Schrotenboer (2018)

13 simple types• 11 numeric types

signed and unsigned integer types: sbyte, byte, short, ushort, int, uint, long, ulong

floating-point types: float, double,decimal• 2 non-numeric types

Unicode character type: char Boolean type: bool

3 nonsimple types• string: array of Unicode characters• object: base type of all other types• dynamic: used in assemblies

16 Predefined Types

Solis and Schrotenboer (2018)

16 Predefined Types

Modified after Solis and Schrotenboer (2018)

128-Bit 32-Bit 64-Bit

8-Bit 16-Bit

Console.WriteLine("size of int = "+sizeof(int)+" bytes");

these have no predefined size

Simple Types

Simple Types

Whitaker (2017)

Nonsimple Types

Solis and Schrotenboer (2018)

Numbers in code are called "numeric literal" Decimal literals

• int x = 1; float pi = 3.14f;

Scientific notation or E notation• float y = 12.3e4f, a = 1.3E5F;

Binary literals• int b = 0b0010110;

Hexadecimal literals• int c = 0xFA09CD;

Digit separator (underscore _)• int a = 1_234_567_890;

• float m = 3_123.223_456f;• long n = 0b1100100_10101010;

Numeric Literals

Whitaker (2017)

There are 6 kinds of types the user can create• enum type• array type• struct type• class type• delegate type• interface type

User-Defined Types

Solis and Schrotenboer (2018)

"A running program uses two regions of memory to store data: stack and heap."

"Stack is a last-in, first-out (LIFO) data structure." "Data can be added to and deleted only from the top." Placing a data item at the top of stack is called pushing the

item onto the stack. Deleting an item from the top of stack is called popping the

item from the stack. Stack memory stores several types of data

• value of certain type of variables, e.g., local variables• program's current state of execution• parameters passed to methods

Stack and Heap

Solis and Schrotenboer (2018)

Stack

Solis and Schrotenboer (2018)

"Data can be stored and removed from the heap in any order."

Heap

Solis and Schrotenboer (2018)

Garbage Collector (GC)

Solis and Schrotenboer (2018)

"Variable is a name representing data stored in memory during program execution."

There are 4 kinds of variables in C#:• local variable: variables declared in a method• field: variables declared in a class or struct• parameter: variables storing method's arguments• array element

Variable

Solis and Schrotenboer (2018)

"A variable must be declared before it is used." "Variable declaration accomplishes 2 things:

• it gives the variable a name and associates a type with it• it allows the compiler to allocate memory for it

Variable Declaration

Solis and Schrotenboer (2018)

"When a variable is declared, you can optionally use the declaration to initialize its memory to a specific value."Example: int a = -1, b = 3;

"Some kinds of variables are automatically set to default values if they are declared without an initializer."

Variable Initialization

Solis and Schrotenboer (2018)

Variable Storage/Initialization

Solis and Schrotenboer (2018)

"Variable declaration includes the type of variable." "This allows the compiler to determine the amount of

memory required at run time and which parts should be stored on the stack and which in the heap."

"The type of variable is determined at compile time and cannot be changed at run time."

Static Typing

Solis and Schrotenboer (2018)

C# compiler has a feature called type inference which can determine the type of a variable based on its value.

When a variable is declared using the var keyword, the compiler will determine its type automatically.

var a = 1;

var b = 1.0F;

var c = 2.1;

var d = "hi";

In Visual Studio, when the user can move the mouse to hover over the var keyword, a popup window will state the type inferred for that variable.

Type Inference

Whitaker (2017)

"The type of variable is not resolved until run time." "C# provides dynamic keyword to represent a specific C#

type that knows how to resolve itself at run time." "At compile time, the compiler does not do type checking

on variables of type dynamic."

Dynamic Typing

Solis and Schrotenboer (2018)

"In some situations, you want to indicate that a variable has an invalid value."

"For a variable of reference type, you can set the variable to null."

"For a variable of value type, its memory is allocated whether or not its content is valid."

"Nullable types allow you to create a value-type variable that can be marked as valid or invalid so that you can make sure a variable is valid before using it."

Nullable Types

Solis and Schrotenboer (2018)

"Types are divided into: value types and reference types" Value types store the actual data Reference types store the address of the data which is

located in the heap

Value and Reference Types

Solis and Schrotenboer (2018)

Category of Types

Solis and Schrotenboer (2018)

string a = null; // reference to nothing

int[] b = new int[]{1,2};

b = null;

Operators,

Program Controls,

Array, and Methods

58

Addition a + b

Subtraction a – b

Multiplication a * b

Division a / b

Modulo a % b

(modulo = remainder after division)

Arithmetic Operators

Deitel and Deitel (2010, p. 66)

59

a == b Is a equal to b?a != b Is a not equal to b?a > b Is a greater than b?a < b Is a less than b?a >= b Is a greater than or equal to b?a <= b Is a less than or equal to b?a==1 && b ==2 AND operatora==1 || b ==2 OR operator!a NOT operator

Logical Operators

Deitel and Deitel (2010, p. 70)

60

a = 1; Value of a is set to 1a += 1; a = a+1

a -= 1; a = a-1

a *= 1; a = a*1

a /= 2; a = a/2

a %= 3; a = a%3

Conditional assignment:a = (1<3) ? 2 : 4; a = 2

a = (1>3) ? 2 : 4; a = 4

Assignment Operators

Deitel and Deitel (2010, p. 109)

61

++a Increment a by 1, then use the newvalue of a

a++ Use the current value of a, then increase a by 1

--a Decrement a by 1, then use the newvalue of a

a-- Use the current value of a, then decrease a by 1

Increment/Decrement Operators

Deitel and Deitel (2010, p. 110)

62

An input from the user can be obtained using the method System.Console.ReadLine()

All input are obtained as character string Numerical input must be converted.

Examplestring input = Console.ReadLine();

int a = Convert.ToInt32(input);

float b = Convert.ToSingle(input);

double c = Convert.ToDouble(input);

decimal d = Convert.ToDecimal(input);

User Input from the Console

Whitaker (2017)

63

Type casting is the conversion of one type to another. There are 2 kinds of type casting

• implicit casting: automatic conversionfloat a = 1.2f + 3; 3 is converted to float

• explicit castingfloat b = (float) 2; integer to floatfloat c = (float) 2.0; double to floatfloat d = Convert.ToSingle("3");

float e = float.Parse("3.14");

Type Casting

Whitaker (2017)

64

Numerical value of 𝜋 and edouble area = Math.PI * r * r;

double e = Math.E;

Minimum and maximum values of numeric typesint max = int.MaxValue;

int min = int.MinValue;

Mathematical functionsdouble a = Math.Sin(Math.PI/2.0);

double b = Math.Sqrt(2.0);

double c = Math.Exp(-1.0);

Math

Whitaker (2017)

65

“All programs could be written in terms of only three control structures:” Sequence structure Selection structure Repetition structure

Control Structures

Deitel and Deitel (2010, p. 88)

66

Statements are executed one after another.

Sequence Structure

Deitel and Deitel (2010, p. 89)

a = 1

b = 2

c = a + b

a = 1;

b = 2;

c = a + b;

Process 1

Process 2

Process 3

Flo

wch

art

Terminator

Terminator

Begin

End

Flow line

67

Selection Structure: if

Deitel and Deitel (2010, p. 90)

b = 1

false

if (a > 0) {

b = 1;

}

Decision a > 0

Connector

true

if (a > 0)

b = 1;or

Flow line

68

Selection Structure: if…else

Deitel and Deitel (2010, p. 92)

b = 1false

a > 0true

if (a > 0)

b = 1;

else

b = 2;

b = 2

69

if…else if…else

if (a == 0)

b = 1;

else if (a > 0)

b = 2;

else

b = 3;

70

Using bool in Decision Making

bool draw = true;

if (draw)

b = 1;

else

b = 3;

bool c = (b > 2);

71

Switch Statementint menu = 2;

switch (menu) {

case 1:

Console.Write("Menu 1");

break;

case 2:

Console.Write("Menu 2");

break;

default:

break;

}

Types allowed with switch: bool, string, any integral types (e.g. byte, long).

Each case requires break

72

Repetition Structure: while

Deitel and Deitel (2010, p. 96)

a++

false

a < 10true

a = 0;

while (a < 10) {

a++;

}

73

Repetition Structure: do…while

Deitel and Deitel (2010, p. 146)

a++

false

a < 10true

a = 0;

do {

a++;

} while (a < 10);

a = 0;

74

Repetition Structure: for

Deitel and Deitel (2010, p. 136)

a = 0

false

a < 10true

for (a = 0; a<10; a++) {

printf(“a = %d\n”, a);

}

Print a a++

Array

75

Array stores objects of the same type. Array declaration:

int[] a = new int[5];

int[] b = new int[]{ 1, 2, 3 };

Accessing array element: int c = a[0];

Array length: int l = a.Length;

Multidimensional array:int[,] d = new int[2,2];

d[0,0] = 1; d[0,1] = 2;

d[1,0] = 3; d[1,1] = 4;

int n1 = d.GetLength(0);

int n2 = d.GetLength(1);Whitaker (2017)

Array of Arrays

76

int[][] a = new int[2][];

a[0] = new int[2];

a[1] = new int[3];

for (int i=0; i<a.Length; i++) {

for (int j=0; j<a[i].Length; j++) {

Console.Write(a[i][j]);

}

}

Whitaker (2017)

foreach Loop

77

int[] a = new int[10];

foreach (int b in a) {

Console.WriteLine("b = "+b);

}

Whitaker (2017)

78

“Enumerations are user-defined variables."Example:enum Days { Sunday, Monday, Tuesday,

Wednesday, Thursday, Friday, Saturday};

Days today = Days.Monday;

if (today == Days.Sunday)

...

else

...

Assigning numbers to enumeration values:enum Days { Sunday = 1, Monday, ... };

enum Months { Jan = 1, Feb = 2, ... };

Enumerations

Whitaker (2017)

79

"Methods are a way of creating reusable codes."Method is also called function, subroutine, or procedure.

The Main function with program arguments:

using System;

class Program {

static void Main(string[] args) {

if (args.Length > 0) {

int a = int.Parse(args[0]);

Console.WriteLine($"a = {a}");

}

}

Methods

Whitaker (2017)

80

using System;

class Program {

static void Main(string[] args) {

Hello();

Console.Write("1+2={0}",Sum(1,2));

}

static void Hello() {

Console.WriteLine("Hello");

}

static int Sum( int a, int b ) {

return a+b;

}

}

Creating a Method

81

Two methods can have the same name if they have different signature (type and order of parameters).

static int Multiply(int a, int b) {

return a*b;

}

static int Multiply(int a,int b,int c){

return a*b*c;

}

Method Overloading

Whitaker (2017)

82

Recursive method is a method that calls itself.

Example:

static int Factorial(int n) {

if (n == 1)

return 1;

return n*Factorial(n-1);

}

Recursive Method

83

Visual Studio's IntelliSense will immediately show XML documentation where the method is used.

/// <summary>Multiply 2 numbers</summary>

/// <param name="a">first number</param>

/// <param name="b">second number</param>

/// <return>product of the 2 numbers</return>

static int Multiply(int a, int b) {

return a * b;

}

XML Documentation

Whitaker (2017)

Object-Oriented

Programming (OOP)

85

Object class is a type or category of objects. Object instance is a specific occurrence of an

object class. Example of class and instanceclass Student {

public int ID;

public string name;

private float grade;

}

Student s = new Student();

s.ID = 123; s.name = "John";

Class and Instance of Object

Whitaker (2017)

86

Constructor is a special method for creating an instance of a class.

Example:class Student {

int ID; string name;

public Student() {

ID = 1; name = "undefined";

}

public Student(int ID, string name) {

this.ID = ID; this.name = name;

}

}

Constructor

87

Methods are member of a class. Example:class Student {

int ID; string name;

public int GetId() {

return ID;

}

public string GetName() {

return name;

}

}

Methods

88

static keyword is used to create something that is shared across all instances of a class.

static keyword can be used with variable, method, class.

Static variable: if an instance changes a value of a static variable, all other instances will access the new value too.

Static method can be accessed using the class name instead of through an instance.

"static" Keyword

89

Property is a class member for access of a private field and can be used as if it is a public field.class Car {

private double speed;

public double Speed {

get { return speed; }

set {

speed = value;

if (speed < 0.0) speed = 0.0;

}

}

Car c = new Car(); c.Speed = 80.0;

double s = c.Speed;

Properties

90

Auto-implemented property:public double Speed { get; set; }

Read-only auto-implement property (must be initialized in a constructor):public class Car {

double Speed { get; }

public Car(double s) { Speed = s; }

}

Default values: (cannot be used in struct)public class Car {

double Speed { get; set; } = 50.0;

}

Properties

91

public class Car {

double Speed { get; set; }

string Model { get; set; }

}

Car c = new Car(){

Speed = 100.0, Model = "Honda"

};

Object Initializer Syntax

92

struct is similar to class but struct is a value type while class is a reference type.

When a struct is assigned from one variable to another, the struct is copied.

struct is passed by value to a method. User cannot create a parameterless constructor.

struct CarStruct {

public double Speed { get; set; }

public void SpeedUp() {

Speed += 10.0;

}

}

Struct(ure)

93

Generics is a way to create a class, struct, or method that can be used with any data type.Example: generic classpublic class Util<T> {

public static T Add(T a, T b) {

return (dynamic)a+b;

}

}

class Program {

static void Main() {

Console.WriteLine(Util<int>.Add(1, 2));

Console.WriteLine(Util<double>.Add(1.1,2.2));

Console.WriteLine(Util<string>.Add("H","i"));

}

}

Generics

94

class Program {

public static T Add<T>(T a, T b) {

return (dynamic)a+b;

}

static void Main() {

Console.WriteLine(Add<int> (1, 2));

Console.WriteLine(Add<double> (1.1,2.2));

Console.WriteLine(Add<string> ("H","i"));

}

}

Generic Method

95

List is similar to array but List can be resized while array size is fixed. List is a generic class.Example:List<int> list = new List<int>;

// add item to the end of list

list.Add(100);

list.Add(20);

list.Add(400);

// insert item at the beginning

list.Insert(0, 20);

// get item

int a = list.ElementAt(0);

int b = list[0];

List Class

96

// remove item

list.RemoveAt(0);

// remove everything in the list

list.Clear();

// convert List to array

int[] a = list.ToArray();

// foreach loop

foreach (int n in list) { }

// initializer syntax

List<int> list = new List<int>() {1,2,3};

List Class

97

Dictionary<TKey,TValue> is a List<T> of mapping of key/value pairs.Example:using System;

using System.Collections.Generic;

class Program {

static void Main() {

Dictionary<string,string> dict =

new Dictionary<string,string>();

dict.Add("John", "080-123-4567");

dict.Add("Jack", "085-987-6543");

Console.WriteLine("John: "+dict["John"]);

Console.WriteLine("Jack: "+dict["Jack"]);

}

}

Dictionary Class

98

Namespace is a collection of types. Fully qualified name is the combination of namespace

name and type name.Example: System.Console.Write();

"using directives indicate which namespace to look in for unqualified type names."

"using static directive can be added for static class, a method can be used without class name."Example: using static System.Console;

static void Main() {

WriteLine("Hi");

}

Namespace

99

using System;

using System.IO;

class Program {

static void Main() {

string text = "Hello\nWorld";

string fileName = "hello.txt";

File.WriteAllText(fileName,text);

}

}

Write Text File: Example 1

100

using System;

using System.IO;

class Program {

static void Main() {

string[] text = new string[3];

text[0] = "Line 1";

text[1] = "Line 2";

text[2] = "Line 3";

string fileName = "multiline.txt";

File.WriteAllLines(fileName,text);

}

}

Write Text File: Example 2

101

using System;

using System.IO;

class Program {

static void Main() {

string text1 =

File.ReadAllText("hello.txt");

string[] text2 =

File.ReadAllLines("multiline.txt");

Console.WriteLine(text1);

foreach (string t in text2)

Console.WriteLine(t);

}

}

Read Text File: Example 1

102

using System; using System.IO;

class Product {

public string Name { get; set; }

public double Price { get; set; }

}

class Program {

static void WriteCSV(Product[] products) {

string text = "Name,Price\n";

foreach (Product p in products)

text += $"{p.Name},{p.Price}\n";

File.WriteAllText("products.csv", text);

}

static void Main() {

Product[] products = new Product[2];

products[0] = new Product()

{ Name = "Keyboard", Price = 900.0 };

products[1] = new Product()

{ Name = "Mouse", Price = 1000.0 };

WriteCSV(products);

}

}

Write CSV File

103

using System; using System.IO;

class Product {

public string Name { get; set; }

public double Price { get; set; }

}

class Program {

static void ReadCSV(string fileName) {

string[] text = File.ReadAllLines(fileName);

Product[] products = new Product[text.Length];

for (int i=1; i<text.Length; i++) {

string[] tokens = text[i].Split(',');

products[i-1] = new Product()

{Name = tokens[0], Price = Double.Parse(tokens[1])};

}

}

static void Main() {

ReadCSV("products.csv");

}

}

Read CSV File

104

using System;

using System.IO;

class Program {

static void Main() {

FileStream fs =

File.OpenWrite("hello.txt");

StreamWriter w = new StreamWriter(fs);

w.Write(100);

w.Write("Hello");

w.Close();

}

}

Write Text File: Example 3

105

using System;

using System.IO;

class Program {

static void Main() {

FileStream fs =

File.OpenRead("hello.txt");

StreamReader r = new StreamReader(fs);

// read a single character at a time

char c = (char) r.Read();

// read one line

string line = r.ReadLine();

r.Close();

}

}

Read Text File: Example 2

106

FileStream fs = File.OpenWrite("hello.bin");

BinaryWriter writer = new BinaryWriter(rs);

writer.Write(3);

writer.Write("Hello");

writer.Close();

Write Binary File

107

FileStream fs = File.OpenRead("hello.bin");

BinaryReader reader = new BinaryReader(fs);

int number = reader.ReadInt32();

string text = reader.ReadString();

reader.Close();

Read Binary File

108

Exceptions are errors that happen at runtime. If code might have a problem, we should wrap it inint number;

try {

Console.Write("Enter a number: ");

string input = Console.ReadLine();

number = int.Parse(input);

}

catch (Exception e) {

Console.WriteLine("Input is invalid");

}

finally {

// codes here always get executed

}

Exception Handling

Common Exceptions

Whitaker (2017, p. 198)

110

Delegate is a user-defined type used to create objects containing references to methods.Declaring delegate type:

Creating delegate object:

Delegate

Solis and Schrotenboer (2018)

111

delegate void Print(int value);

class Program {

void Print1(int value) {...}

void Print2(int value) {...}

static void Main() {

Program p = new Program();

Print del = new Print(p.Print1);

del += p.Print2;

del(100);

}

}

Delegate: Invocation List

Solis and Schrotenboer (2018)

112

Delegate is a user-defined type used to create objects containing references to methods.Example:delegate void Print(int value);

class Program {

void Print1(int value) {

Console.Write($"{value}");

}

static void Main() {

Program p = new Program();

Print del = new Print(p.Print1);

del(100);

}

}

Delegate

113

Example:delegate int Add(int value);

class Program {

static void Main() {

Add a1 = (x) => { return x+1; };

Add a2 = x => x+2;

Console.WriteLine(""+a1(1));

Console.WriteLine(""+a2(1));

}

}

Lambda Expression

114

"When an event occurs, other parts of the program are notified that the event has occurred."

Publisher/SubscriberPublisher: a class defining an eventSubscriber: a class supplying the publisher a method called back when the event occurs.

Event

Solis and Schrotenboer (2018)

115

An event contains a private delegate

Event

Solis and Schrotenboer (2018)

116

Publisher / Subscriber

Solis and Schrotenboer (2018)

117

Declaring an Event

Solis and Schrotenboer (2018)

118

Subscribing to an Event

Solis and Schrotenboer (2018)

119

Example: Raising an Event

Solis and Schrotenboer (2018)

120

Example: Handling an Event

Solis and Schrotenboer (2018)

121

Example: Main Program

Solis and Schrotenboer (2018)

122

using System;

delegate void Handler();

class Program {

public event Handler e;

public Program() { this.e += Print; }

public void Print() {

Console.WriteLine("i = 10");

}

public void Count() {

for (int i=0; i<100; i++) {

if ( i==10 && e != null)

e();

}

}

static void Main() {

Program p = new Program();

p.Count();

}

}

Event: Example

123

"Interface is a reference type that specifies a set of function members but does not implement them."The implementation of these functions are done by the class or struct that implements the interface.

Example:interface IPerson {

string GetName();

}

class A: IPerson { // implements IPerson

public string name;

public string GetName() { return name; }

}

Interface

124

class B: IPerson {

public string first, last;

public string GetName() {

return first+" "+last;

}

}

class Program {

static void Print( IPerson p ) {

Console.Write("Name:{0}",p.GetName());

}

static void Main() {

A a = new A() { name = "Jack" };

B b = new B() { first = "John", last="Ma" };

Print(a);

Print(b);

}

}

Example (continued)

125

An array of numbers can be sorted.Example:using System;

class Program {

static void Main() {

var num = new [] { 20, 4, 16 };

Array.Sort(num);

foreach (var i in num)

Console.Write($"{i}");

}

}

However, if you try to sort a user-defined class, you might get an exception.

IComparable Interface

126

Example:using System;

class MyClass { public int value; }

class Program {

static void Main() {

MyClass[] m = new MyClass[5];

...

Array.Sort(m); // exception thrown

}

}

IComparable Interface

127

IComparable interface is defined by .NET BCL asinterface IComparable {

int CompareTo( object obj );

}

The CompareTo method should return one the following values:

IComparable Interface

128

IComparable Example

129

IComparable Example

130

An interface cannot contain data or static members An interface can contain only nonstatic function

members: methods, properties, events, indexers The declaration of these function members cannot

contain the implementation. Interface name normally starts with uppercase I

Declaring an Interface

131

An

Implementing an Interface

Windows Forms

133

using System.Drawing;

…private void panel1_Paint(object sender, PaintEventArgs e) {

Graphics g = e.Graphics;Pen pen = new Pen(Color.Black, 1);pen.DashStyle =

System.Drawing.Drawing2D.DashStyle.Dash;pen.Width = 5;

g.DrawLine(pen, p1, p2);

}

Drawing

134

Control is a component with visual representation. All controls are derived from the base class Control defined in the namespace System.Windows.Forms.

A Form is a type of ContainerControl which can contain other controls.

Control

D. Solis and C. Schrotenboer, 2018, Illustrated C# 7, 5th edition, Apress. R.B. Whitaker, 2017, The C# Player's Guide, 3rd edition, Starbound Software. P. J. Deitel, and H. M. Deitel, 2010, C How to Program, 6th edition, Pearson

Education.

References

top related