(2) c sharp introduction_basics_part_i

25
Introductory words: We write programs to solve problems. Now let's inspect a problem that we want to solve... Nico Ludwig (@ersatzteilchen) (2) Introduction of C# Basics – Part I

Upload: nico-ludwig

Post on 26-Dec-2014

41 views

Category:

Technology


3 download

DESCRIPTION

- A Tour through other .Net Programming Languages - C# Syntax Cornerstones

TRANSCRIPT

Page 1: (2) c sharp introduction_basics_part_i

● Introductory words:● We write programs to solve problems.● Now let's inspect a problem that we want to

solve...

Nico Ludwig (@ersatzteilchen)

(2) Introduction of C# Basics – Part I

Page 2: (2) c sharp introduction_basics_part_i

2

TOC● (2) Introduction of C# Basics – Part I

– A Tour through other .Net Programming Languages

– C# Syntax Cornerstones

Page 3: (2) c sharp introduction_basics_part_i

3

Challenge: Parse an Update Log● Userstory: "As an administrator I want to know the latest updates on a PC, in order to get a report of that PC's state!"

● It is needed to parse the file "/Library/Logs/Software Update.log":

2009-04-06 12:43:04 +0200: Installed "GarageBand Update" (5.0.1)

2009-04-06 12:44:34 +0200: Installed "iMovie Update" (8.0.1)

2009-07-30 13:11:28 +0200: Installed "iMovie Update" (8.0.4)

2009-04-06 12:43:31 +0200: Installed "iTunes" (8.1)

● How can we solve this problem?

● The user story describes the problem to besolved in everyday language.

● Now let's inspect how we can solve this problemwith a program. - We are going to discusssolutions in some high level language (HLL).

● What is an HLL?● Allows to express solutions in a more human

readable way. Hardware near languages (e.g.assembly) are hardware specific and notstandardized, HLLs are in opposite hardwareindependent and standardized (so is C#).

● What is a low level language?● A low level language is a machine near

language that works only on one type ofmachine (assembly), so they are often notportable.

Page 4: (2) c sharp introduction_basics_part_i

4

Visual Basic 10 (VB 10)

dImports SystemImports System.IOImports System.Collections.GenericImports System.Text.RegularExpressions

Module ProgramSub Main()

' check arguments from console If (0 < My.Application.CommandLineArgs.Count) Then Dim latestUpdates As IDictionary(Of String, String) = New SortedDictionary(Of String, String) Dim parseRex As Regex = New Regex("[^\""]*\""(?<appName>[^\""]*)\""\s*\((?<versionNo>[^\(]*)\)" ) ' open and check file, read a line For Each aLine As String In File.ReadAllLines(My.Application.CommandLineArgs.Item(0)) ' parse the line: e.g. 2009-04-06 12:42:58 +0200: Installed "Digital Camera Raw Compatibility Update" (2.5) Dim match As Match = parseRex.Match(aLine) If (match.Success) Then ' store the parsed data Dim appName As String = match.Groups.Item("appName").ToString() Dim versionNo As String = match.Groups.Item("versionNo").ToString() If (latestUpdates.ContainsKey(appName)) Then If (0 < String.CompareOrdinal(versionNo, latestUpdates.Item(appName))) Then latestUpdates.Item(appName) = versionNo End If Elsed latestUpdates.Add(appName, versionNo) End If End If Next ' output the collected data to console For Each item As KeyValuePair(Of String, String) In latestUpdates Console.WriteLine("App: {0}, Latest Update: {1}" , item.Key, item.Value) Next End If End SubEnd Module

● A dialect of the Beginner's All-purpose SymbolicInstruction Code (BASIC). - The reputation-problem ofBASIC programmers: the word "Beginner" in the nameof the language!

● VB is a proprietary programming language designed byMicrosoft.

● VB 6 was a very productive language (it provided verygood means of integration on the Windows platform)and its success has been continued with VB running on.Net. The VB languages are very popular in the US.● Its relative, VBA, is an approachable language for

end-users and is used to automate windowsapplications like MS Excel.

● This approachability is also due to the fact that VB iscase-insensitive. - Esp. beginners have often to copewith casing of variable and function names, andexactly this problem is not present in VB.

● VB's code is rather noisy as there exist manykeywords.

● Typically VB-only programmers step into the "4GL-trap": "IDE, technology, framework and language is allVB!" - 4GL-developers can't see a difference here,everything is integrated.

Page 5: (2) c sharp introduction_basics_part_i

5

C++/CLI – Part I

#include "stdafx.h"

using namespace System;using namespace System::IO;using namespace System::Collections::Generic;using namespace System::Text::RegularExpressions;

int main(array<String^>^ args){

// check arguments from console if (0 < args->Length) { IDictionary<String^, String^>^ latestUpdates = gcnew SortedDictionary<String^, String^>(); Regex^ parseRex = gcnew Regex("[^\\\"]*\\\"(?<appName>[^\\\"]*)\\\"\\s*\\((?<versionNo>[^\\(]*)\\)" ); // open and check file, read a line for each (String^ aLine in File::ReadAllLines(args[0])) { // parse the line: e.g. 2009-04-06 12:42:58 +0200: Installed "Digital Camera Raw Compatibility Update" (2.5) Match^ match = parseRex->Match(aLine); if (match->Success) { // store the parsed data

String^ appName = match->Groups["appName"]->ToString(); String^ versionNo = match->Groups["versionNo"]->ToString(); if (latestUpdates->ContainsKey(appName)) { if (0 < String::CompareOrdinal(versionNo, latestUpdates[appName])) { latestUpdates[appName] = versionNo; } } else

● C++/CLI is an ECMA standard (ECMA-372).● C++/CLI is the only ".Net language", in which

native applications can be compiled in VisualStudio.

● ECMA: "European Computer ManufacturersAssociation" in past. But meanwhile only theacronym "ECMA" or "ECMA International" is usedto make the international (and no longereuropean) focus clear.

● C++/CLI (Common Language Infrastructure) isMicrosoft's C++ variant (extension with somesyntactical stuff) for .Net programming. BeforeC++/CLI was present, there was "Managed C++"for .Net, which is meanwhile deprecated.

● For the Windows Runtime (WinRT) there existsanother variant of C++, which is primarily targetedto be used with COM to program apps forWindows 8. - It is called C++/CX (ComponentExtensions). The syntax of C++/CX is similar tothe syntax of C++/CLI, but not all syntactic similaridioms are equivalent.

Page 6: (2) c sharp introduction_basics_part_i

6

C++/CLI – Part II

d { latestUpdates->Add(appName, versionNo); } } } // output the collected data to console for each (KeyValuePair<String^, String^>^ item in latestUpdates) { Console::WriteLine("App: {0}, Latest Update: {1}" , item->Key, item->Value); }

}}

Page 7: (2) c sharp introduction_basics_part_i

7

F# 3

d#lightopen Systemopen System.IOopen System.Text.RegularExpressions

if 2 >= Environment.GetCommandLineArgs().Length thenlet parseRex = new Regex(@"[^\""]*\""(?<appName>[^\""]*)\""\s*\((?<versionNo>[^\(]*)\)")

// open and check file, read the lines, parse and process the data, output the processed data to console File.ReadLines(Environment.GetCommandLineArgs().GetValue(1).ToString()) |> Seq.map(parseRex.Match) |> Seq.filter(fun theMatch -> theMatch.Success) |> Seq.sortBy(fun theMatch -> theMatch.Groups.Item("versionNo").ToString()) |> Seq.map(fun theMatch -> theMatch.Groups.Item("appName").ToString(), theMatch.Groups.Item("versionNo").ToString()) |> dict |> Seq.sortBy(fun item -> item.Key) |> Seq.iter(fun item -> printfn "App: %s, Latest Update: %s" item.Key item.Value)

● This programming language has a completely different but verycompact syntax (in this example), in comparison to the otherlanguages being presented. Often examples in F# are "headblowing" to show the compactest syntax (this was also donedeliberately in this example). We can also code F# programs tosolve real life problems with well-known control flow constructs(like if-branches and for-loops).● In F# whitespaces are significant (off-side rule), if the #light

compiler directive is set. Otherwise a more verbose, butwhitespace-agnostic syntax has to be used (featuring keywordslike begin and end).

● F# is a so-called functional programming language. -Programming constructs don't work like a bunch of statements,rather do they describe the result of the operation, w/o any sideeffect.● In F# all symbols (they are even called values) are immutable

by default!● F# is also special as is it is very typesafe. For almost all kinds of

conversions explicit conversions or casts are required. - On theother hand this is rarely required, as F# has great support fortype inference.

● Such languages are often used in Artificial Intelligence (AI) and theprogramming of interpreters and compilers, for what F# providesspecial tools.

● F# is open source.● F# can also be used as scripting language.

Page 8: (2) c sharp introduction_basics_part_i

8

C# 5 – Part I

using System;using System.IO;using System.Collections.Generic;using System.Text.RegularExpressions;

public class Program{

public static void Main(string[] args){

// check arguments from consoleif (0 < args.Length){

IDictionary<string, string> latestUpdates = new SortedDictionary<string, string>();Regex parseRex = new Regex(@"[^\""]*\""(?<appName>[^\""]*)\""\s*\((?<versionNo>[^\(]*)\)" );// open and check file, read a lineforeach (string aLine in File.ReadAllLines(args[0])){

// parse the line: e.g. 2009-04-06 12:42:58 +0200: Installed "Digital Camera Raw Compatibility Update" (2.5)Match match = parseRex.Match(aLine);if (match.Success){

// store the parsed datastring appName = match.Groups["appName"].ToString();string versionNo = match.Groups["versionNo"].ToString();if (latestUpdates.ContainsKey(appName))

{ if (0 < string.CompareOrdinal(versionNo, latestUpdates[appName])) { latestUpdates[appName] = versionNo; } } else

● With this programming language we'll deal in this workshop.● Created by Microsoft and mainly by Anders Hejlsberg in 2000.

Interestingly Hejlsberg worked for Borland until he went to Microsoft in1996. At Borland he created Turbo Pascal and Delphi.

● C# is an ECMA standard (ECMA-334).● Meanings of the name "C sharp": a "sharp" kind of the C programming

language or C with four pluses.● It's the main programming language of the "language diverse" .Net

platform. - Microsoft does its new stuff first in C#.● Modern multi-paradigm language, a mixture of Java and C++ in syntax.● C-style syntax, simple to use.● Application areas:

● All kinds of application systems.● Good acceptance, because there is a good documentation available

as well as some height quality IDEs allowing Rapid ApplicationDevelopment (RAD). (RAD was already present in Visual Basic (VB)and Delphi, its success is continuing in C#.)● MS Visual Studio (the Express edition is free)● Borland Developer Studio● #develop (free)

Page 9: (2) c sharp introduction_basics_part_i

9

C# 5 – Part II

{ latestUpdates.Add(appName, versionNo); }

}}// output the collected data to consoleforeach (KeyValuePair<string, string> item in latestUpdates){

Console.WriteLine("App: {0}, Latest Update: {1}" , item.Key, item.Value);}

}}

}

Page 10: (2) c sharp introduction_basics_part_i

10

Common Intermediate Language (CIL, also just IL)IL_0001: ldc.i4.1 IL_0002: newarr System.StringIL_0007: stloc.s 08 // CS$0$0000IL_0009: ldloc.s 08 // CS$0$0000IL_000B: ldc.i4.0 IL_000C: ldstr "C:\Users\nludwig\Desktop\application.properties"IL_0011: stelem.ref IL_0012: ldloc.s 08 // CS$0$0000IL_0014: stloc.0 // argsIL_0015: ldc.i4.0 IL_0016: ldloc.0 // argsIL_0017: ldlen IL_0018: conv.i4 IL_0019: clt IL_001B: ldc.i4.0 IL_001C: ceq IL_001E: stloc.s 09 // CS$4$0001IL_0020: ldloc.s 09 // CS$4$0001IL_0022: brtrue IL_0154IL_0028: newobj System.Collections.Generic.SortedDictionary<System.String,System.String>..ctorIL_002D: stloc.1 // latestUpdatesIL_002E: ldstr " [^\"]*\"(?<appName>[^\"]*)\"\s*\((?<versionNo>[^\(]*)\)"IL_0033: newobj System.Text.RegularExpressions.Regex..ctorIL_0038: stloc.2 // parseRexIL_003A: ldloc.0 // argsIL_003B: ldc.i4.0 IL_003C: ldelem.ref IL_003D: call System.IO.File.ReadAllLinesIL_0042: stloc.s 0A // CS$6$0002IL_0044: ldc.i4.0 IL_0045: stloc.s 0B // CS$7$0003IL_0047: br IL_00EFIL_004C: ldloc.s 0A // CS$6$0002IL_004E: ldloc.s 0B // CS$7$0003IL_0050: ldelem.ref IL_0051: stloc.3 // aLineIL_0053: ldloc.2 // parseRexIL_0054: ldloc.3 // aLineIL_0055: callvirt System.Text.RegularExpressions.Regex.MatchIL_005A: stloc.s 04 // matchIL_005C: ldloc.s 04 // matchIL_005E: callvirt System.Text.RegularExpressions.Group.get_SuccessIL_0063: ldc.i4.0 IL_0064: ceq IL_0066: stloc.s 09 // CS$4$0001IL_0068: ldloc.s 09 // CS$4$0001IL_006A: brtrue.s IL_00E8IL_006D: ldloc.s 04 // matchIL_006F: callvirt System.Text.RegularExpressions.Match.get_GroupsIL_0074: ldstr "appName"IL_0079: callvirt System.Text.RegularExpressions.GroupCollection.get_ItemIL_007E: callvirt System.Object.ToStringIL_0083: stloc.s 05 // appNameIL_0085: ldloc.s 04 // matchIL_0087: callvirt System.Text.RegularExpressions.Match.get_GroupsIL_008C: ldstr "versionNo"IL_0091: callvirt System.Text.RegularExpressions.GroupCollection.get_ItemIL_0096: callvirt System.Object.ToStringIL_009B: stloc.s 06 // versionNoIL_009D: ldloc.1 // latestUpdatesIL_009E: ldloc.s 05 // appNameIL_00A0: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.ContainsKeyIL_00A5: ldc.i4.0 IL_00A6: ceqIL_00A8: stloc.s 09 // CS$4$0001IL_00AA: ldloc.s 09 // CS$4$0001IL_00AC: brtrue.s IL_00DAIL_00AF: ldc.i4.0

IL_00B0: ldloc.s 06 // versionNoIL_00B2: ldloc.1 // latestUpdatesIL_00B3: ldloc.s 05 // appNameIL_00B5: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.get_ItemIL_00BA: call System.String.CompareOrdinalIL_00BF: clt IL_00C1: ldc.i4.0 IL_00C2: ceq IL_00C4: stloc.s 09 // CS$4$0001IL_00C6: ldloc.s 09 // CS$4$0001IL_00C8: brtrue.s IL_00D7IL_00CB: ldloc.1 // latestUpdatesIL_00CC: ldloc.s 05 // appNameIL_00CE: ldloc.s 06 // versionNoIL_00D0: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.set_ItemIL_00D8: br.s IL_00E7IL_00DB: ldloc.1 // latestUpdatesIL_00DC: ldloc.s 05 // appNameIL_00DE: ldloc.s 06 // versionNoIL_00E0: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.AddIL_00E9: ldloc.s 0B // CS$7$0003IL_00EB: ldc.i4.1 IL_00EC: add IL_00ED: stloc.s 0B // CS$7$0003IL_00EF: ldloc.s 0B // CS$7$0003IL_00F1: ldloc.s 0A // CS$6$0002IL_00F3: ldlen IL_00F4: conv.i4 IL_00F5: clt IL_00F7: stloc.s 09 // CS$4$0001IL_00F9: ldloc.s 09 // CS$4$0001IL_00FB: brtrue IL_004CIL_0101: ldloc.1 // latestUpdatesIL_0102: callvirt System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.String>>.GetEnumeratorIL_0107: stloc.s 0C // CS$5$0004IL_0109: br.s IL_012FIL_010B: ldloc.s 0C // CS$5$0004IL_010D: callvirt System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<System.String,System.String>>.get_CurrentIL_0112: stloc.s 07 // itemIL_0115: ldstr "App: {0}, Latest Update: {1}"IL_011A: ldloca.s 07 // itemIL_011C: call System.Collections.Generic.KeyValuePair<System.String,System.String>.get_KeyIL_0121: ldloca.s 07 // itemIL_0123: call System.Collections.Generic.KeyValuePair<System.String,System.String>.get_ValueIL_0128: call System.Console.WriteLineIL_012F: ldloc.s 0C // CS$5$0004IL_0131: callvirt System.Collections.IEnumerator.MoveNextIL_0136: stloc.s 09 // CS$4$0001IL_0138: ldloc.s 09 // CS$4$0001IL_013A: brtrue.s IL_010BIL_013C: leave.s IL_0152IL_013E: ldloc.s 0C // CS$5$0004IL_0140: ldnull IL_0141: ceq IL_0143: stloc.s 09 // CS$4$0001IL_0145: ldloc.s 09 // CS$4$0001IL_0147: brtrue.s IL_0151IL_0149: ldloc.s 0C // CS$5$0004IL_014B: callvirt System.IDisposable.DisposeIL_0151: endfinally

● IL is the very low level language specified by theCLI.● This piece of IL was generated from C# 5 code. It

was generated in debug mode, which generatesnop op-codes, which makes debugging easier andline numbers. The nops have been removed.

● IL is a platform independent, object oriented andstack-based assembly language.

● Translation:● E.g. a C# compiler will generate IL from a piece of

C# code.● Then, as another part of the building procedure,

the IL code will be assembled into so-calledbytecode. The result is a CLI assembly.

● During run time the bytecode will be translatedinto native machine code (by a JIT compiler of thenative runtime) and then it will be executed.

Page 11: (2) c sharp introduction_basics_part_i

11

What is the C# programming language?

● C# is standardized in ECMA-334.

● C# blends features of C++, Java and other popular languages.

– Without C# being based on Java, .Net would not have been a success!

● A CLS compliant language, ECMA and ISO/IEC standard.

● Major platform is Windows (compilers and CLR from MS).

● ECMA: "European Computer ManufacturersAssociation" in past. But meanwhile only theacronym "ECMA" or "ECMA International" is usedto make the international (and no longereuropean) focus clear.

● ISO/IEC: International Standards Organization,International Electrotechnical Commission.

● There also exists a port to unix-like OS'(Unix/Linux/Mac OS) that is called "Mono".

Page 12: (2) c sharp introduction_basics_part_i

12

12

C# Core Features

● Multiparadigm language.

● Static typing by default.

● C-style syntax with extensions.

● CTS is the first class type system.

● C# is popular and evolving.

– Relatively short innovation cycles. Learned stuff gets stale early (~two years).

● C# is relatively simple to learn.

– It is basically pointer free. (We could use pointers. The CTS doesn't use pointers.)

– It doesn't use manual memory management, the runtime has a garbage collector.

● Functional, oo and imperative.● But mainly imperative (i.e. from top to bottom).

● We can use pointers to memory:● To access Win32 APIs (written in C).● Only in unsafe contexts.

● The syntax is similar to C:● Blocks (i.e. {}).● Statements, delimited by semicolons and

expressions.● Operators and comments● Imperative execution of a program.

● CTS is present for programming.● int, bool and string are present as keywords.

● Good acceptance, because there is a gooddocumentation available as well as some IDEs.● MS Visual Studio (the Express edition is free)● #develop (free)

Page 13: (2) c sharp introduction_basics_part_i

13

● What we called member function in C++ is called method in .Net/C#.● The using directive tells the compiler to use the specified namespace. The types, which are used by

the program, are defined in the namespace System and the using directive makes that types (e.g.Console) known to the compiler.● The namespace System contains the core .Net types.● Referenced libraries (i.e. assemblies) must be added into the project.

● A type can reside in a namespace that makes the type unique, so that it can be qualified.● The type. All assemblies have to define types in general. Here the class Program defines the type

Program.● Types define code that resides in methods.● Methods are functions, which are presented by a type.● The execution of a C# program starts in Main(). I.e. each C# application must provide a Main()

method.● An array of strings is passed to Main(); Main() does not return a value to the caller.

● What is an array?● What data could be contained in that array?● What data could be returned by Main()?

● Main() must be called w/o having an object of the type Program, therefor it is declared as static method.● (Non static methods will be introduced later.)

● The code of methods contains statements and expressions.● What's the difference?

● A statement consists of expressions; expressions have a type; statements end withsemicolons. There also exist empty statements (a standalone semicolon).

● In methods' code typically new objects will be created and methods will be called on them.● In this Main() method a message will be output to the console.

● How does console input and output work?

13

Structure of a C# Console Application

// Program.csusing System;

namespace ConsoleApplication{

public class Program{

// The execution of a program always starts in the method Main().public static void Main(string[] args){

Console.WriteLine("Hello World!");}

}}

Page 14: (2) c sharp introduction_basics_part_i

14

Code Snippets● Hence we'll begin using snippets as code examples, i.e. no Main() etc.!

● In the end no fully runnable program code will be shown in upcoming lectures!

// Program.csusing System;

namespace ConsoleApplication{

public class Program{

public static void Main(string[] args){

Console.WriteLine("Hello World!");}

}}

Console.WriteLine("Hello World!");

Page 15: (2) c sharp introduction_basics_part_i

15

● What keywords do you know from anyprogramming languages?

● Syntax versus semantics; what's that?● Grammar/keywords versus their meaning.

● In programming errors can occur on different"times". Can you explain this statement?● (In C/C++ there also exits the link time, during

which errors can happen.)

15

C# as a compiled Language

● C# reserves symbols for its grammar, these are called keywords.

● Syntax versus Semantics:

– Both statements do not mean the same, but the syntax is similar!

– Locals need to be initialized, uninitialized fields have default values.

● Compile time errors versus run time errors:

– Both statements are ok for the compiler.

● But the last one throws a DivisionByZeroException at run time.

int count = 2;

count = 2;

int zero = 0;int oddResult = 42/zero;

Page 16: (2) c sharp introduction_basics_part_i

16

C# Syntax Cornerstones – Part I – Imperative Elements

● Basic elements: expressions, statements, blocks. They can be freely formatted.

– Imperative programming: Statements and blocks are executed sequentially.

– The order of execution of expressions is strictly defined in C#!

● The most elementary statements are variable definitions.

– Variable definitions make variables applicable in the code.

– By default, variables need to be typed on definition, this is called static typing.

● Implicit and dynamic typing is also possible, but we stick to explicit static typing in this course.

● Besides definition, variables can be initialized and assigned to.

– Initialization gives initial values to a variable.

– Assignment sets a variable to a new value.

if (answerIsOk) {Console.WriteLine("Result: "+(3 + 4));

}

int age = 19;

age = 25;

double width = 32.8;

● In C# multiple variables of the same type can bedefined/declared in one statement.

Page 17: (2) c sharp introduction_basics_part_i

17

C# Syntax Cornerstones – Part II – Types

● Primitive types are integrated types, whose objects can be created with literals.

– Simple value integral types: int, long (etc.).

– Simple value float types: float, double (etc.).

– Simple value boolean type: bool.

– Simple value character type: char.

– Reference text type: string. (an alias C# keyword for the .Net type System.String)

– We can create compile time constants (const) of primitive type.

● There exist value types (e.g. int) and reference types (e.g. string).

– Variables of reference type are often simply called references.

● Explicit type conversion:

– Explicit conversions are done with explicit casts or the as operator.

– Explicit conversions can be done safely with checked expressions and contexts.

– The type System.Convert (various types) and the methods ToString()/Parse() (string).

// Conversion with cast:int i = (int)2.78;

// Conversion with as:string text = choice as string;

● What are primitive types?● The text "Hello World" is not stored like today's date or the number 42. To work efficiently with data C# offers primitive

data types, which are constrained to a specific type of information.● These types are integrated into C# (as keywords), the compiler can directly deal with them, e.g. it knows how to

compare them (not for string, as the string's methods need to be called). Also the CLR has integrated support forprimitive types.

● What is a literal?● A literal is a value of specific type that can be written out in source code directly.● In a sense a literal is the opposite of a symbol.

● The type unsigned int is not CLS compliant => Do use the type int instead of unsigned int primarily.● Literals? C# does not define octal literals (C/C++ and Java do).

● The float datatypes can't be compared with ordinary operators, because of different accuracies. Use double.Epsilon forcomparisons (double.Epsilon > Math.Abs(value1 - value2)). The type double should be used primarily instead of float.● Literals? In C# we can use the D/d suffix for literals of type double (not in C/C++ or Java).

● The bool type describes logical values. The expressions used in control structures are of type bool.● Literals?

● The type char is an integral type. A string is composed of multiple chars.● Important: string objects are immutable, instead of C++' std::strings, which are modifiable! string-operations create

new string objects.● C# knows some escape characters and provides verbatim strings.● strings and chars are unicode based (having a size of 2B).

● For us as learners of the C# language the usage of the keywords var and dynamic is forbidden.● Type conversion:

● A type conversion from a smaller type to a greater type works implicitly, if the types are "related" (char -> int).● A type conversion from a greater type to a smaller type must be done explicitly, and is only allowed, if the types are

"related" (int -> char). This casting must be done explicitly, because there is the chance that data will be lost on thatconversion from a greater to a smaller type.

● The class Convert provides some methods, with which some conversions of non-related types can be performed.● The Parse() and ToString() methods of the primitive types can be used to convert numeric or logical values from or to

strings.● The checked context allows to check an overflow during the conversion of values.

● Why is it needed to check for overflow? Why is it dangerous?● In C# arithmetic operations are only possible with 32b and 64b values.● byte b = 100;● b = (byte) (b + 200); The variable b and the value 200 will be converted to 32b ( int) values each, then the addition

will be executed and then that result must be explicitly cast to a byte. The sum (the value 300) of 32b will not fit intobyte, so a part of 300 will overflow (the most significant bits of the result will be discarded) and 44 will make up theresult of b. With the expression checked((byte)(b + 200)), this overflow wouldn't happen, instead anOverflowException would be thrown! Often overflows are errors (but sometimes it is part of the algorithm, e.g. forhash calculation). The keyword checked will replace overflowing operators with throwing ones (add -> add.ovf inthis example (only for add, mul, sub and conv)), nothing else.

● We can activate checking for arithmetic overflow and underflow for the whole VS project w/o using the checked keyword (then checked is the default for arithmetic operations). - This option is not activated when we create a newVS project.

● Only integral and the decimal will overflow, other floating point types can handle infinity.

Page 18: (2) c sharp introduction_basics_part_i

18

C# Syntax Cornerstones – Part III – Identifiers andComments

• C# uses case sensitive identifiers, we have to obey common conventions.

– aString is not the same identifier as aStRiNg!

– We've to use a common notation (e.g. camelCase or PascalCase) as convention!

– Language specific characters can be used (e.g. umlauts) as well as the underscore.

– C# keywords mustn't be used as identifiers.

• Comments can be applied everywhere in code. We should exploit comments!

• The usage and definition of methods will be discussed later.

– Methods are .Net's pendant of functions/member functions in other languages.

• In the next slides we're going to understand the most important operators in C#.

/* commented */ /** commented */ // commented /// commented (triple slash)

● What are primitive types?● The text "Hello World" is not stored like today's date or the number 42. To work efficiently with data C# offers primitive

data types, which are constrained to a specific type of information.● These types are integrated into C# (as keywords), the compiler can directly deal with them, e.g. it knows how to

compare them (not for string, as the string's methods need to be called). Also the CLR has integrated support forprimitive types.

● What is a literal?● A literal is a value of specific type that can be written out in source code directly.● In a sense a literal is the opposite of a symbol.

● The type unsigned int is not CLS compliant => Do use the type int instead of unsigned int primarily.● Literals? C# does not define octal literals (C/C++ and Java do).

● The float datatypes can't be compared with ordinary operators, because of different accuracies. Use double.Epsilon forcomparisons (double.Epsilon > Math.Abs(value1 - value2)). The type double should be used primarily instead of float.● Literals? In C# we can use the D/d suffix for literals of type double (not in C/C++ or Java).

● The bool type describes logical values. The expressions used in control structures are of type bool.● Literals?

● The type char is an integral type. A string is composed of multiple chars.● Important: string objects are immutable, instead of C++' std::strings, which are modifiable! string-operations create

new string objects.● C# knows some escape characters and provides verbatim strings.● strings and chars are unicode based (having a size of 2B).

● For us as learners of the C# language the usage of the keywords var and dynamic is forbidden.● Type conversion:

● A type conversion from a smaller type to a greater type works implicitly, if the types are "related" (char -> int).● A type conversion from a greater type to a smaller type must be done explicitly, and is only allowed, if the types are

"related" (int -> char). This casting must be done explicitly, because there is the chance that data will be lost on thatconversion from a greater to a smaller type.

● The class Convert provides some methods, with which some conversions of non-related types can be performed.● The Parse() and ToString() methods of the primitive types can be used to convert numeric or logical values from or to

strings.● The checked context allows to check an overflow during the conversion of values.

● Why is it needed to check for overflow? Why is it dangerous?● In C# arithmetic operations are only possible with 32b and 64b values.● byte b = 100;● b = (byte) (b + 200); The variable b and the value 200 will be converted to 32b ( int) values each, then the addition

will be executed and then that result must be explicitly cast to a byte. The sum (the value 300) of 32b will not fit intobyte, so a part of 300 will overflow (the most significant bits of the result will be discarded) and 44 will make up theresult of b. With the expression checked((byte)(b + 200)), this overflow wouldn't happen, instead anOverflowException would be thrown! Often overflows are errors (but sometimes it is part of the algorithm, e.g. forhash calculation). The keyword checked will replace overflowing operators with throwing ones (add -> add.ovf inthis example (only for add, mul, sub and conv)), nothing else.

● We can activate checking for arithmetic overflow and underflow for the whole VS project w/o using the checked keyword (then checked is the default for arithmetic operations). - This option is not activated when we create a newVS project.

● Only integral and the decimal will overflow, other floating point types can handle infinity.

Page 19: (2) c sharp introduction_basics_part_i

19

Operator Notations – Arity

● Binary operators

● Unary operators

● Ternary operator

// Addition as binary operator:int sum = 2 + 3;

// Increment as unary operator:int i = 1;++i; // Increments i (the result is 2).

// The conditional operator is the only ternary operator:int i = 2;int j = 3;string answer = (i < j) ? "i less than j" : "i not less than j";

● What are binary operators?● These operators have an arity of two, i.e. they

have two operands.● The operator is written in between the operands

(infix notation).● Which other binary operators do you know?

● What are unary operators?● These operators have one operand.● There exist prefix and postfix operators.

● Increment and decrement operators -> usefulin loops!

● What are ternary operators?● The decision operator ?: (sometimes we call it

"Elvis operator").

Page 20: (2) c sharp introduction_basics_part_i

20

Operator Notations – Placement

● Prefix operators

● Postfix operators

● Infix operators

// Negation as prefix operator:bool succeeded = !failed;

// Increment as postfix operator:int result = item++;

// Addition as infix operator:int sum = 2 + 3;

Page 21: (2) c sharp introduction_basics_part_i

21

Mathematical Operators

● Binary +, - and *, / are known form elementary mathematics.

– Attention: Integer division yields an integer result!

– The result of the division by 0 results in a run time error.

● A DivisionByZeroException will be thrown.

● Unary – and + as sign-operators.

● Somewhat special: ++/-- and %

● Math.Log(), Math.Pow() and other operations in the class Math.

● Bit operations work with integers as arguments and result in integers.

– Operators: ^, |, &, ~, <<, >>

● What does that mean "integral division has aninteger result"?● I.e. the results are no floating point values!

● Integral division: How to do that in a correct way?● Use casts or the correct literals on/for any of the

operands!● The division by 0 is not "not allowed" in maths,

instead it is "just" undefined.● What does the operator % do?

● This operator doesn't calculate the modulus,instead it calculates the remainder!

● Why do we need bitwise operators?

Page 22: (2) c sharp introduction_basics_part_i

22

Other Operators and Operator Overloading

● Assignment and combined assignment.

– Operators: =, +=, *=, /= etc.

– Operators: &=, |=, ^=, <<=, >>=

● Concatenation of strings with the operators + and +=.

– But: strings are still immutable!

● Important extra operators:

– Operators: [], (), ?:, ??, new, is, as, typeof

– Operators: ., ::

– Operators: *, ->, sizeof

– Operators: =>

● C# permits to redefine (overload) operators for user defined types UDT.

int i = 12;i = i + 2; // (i = 14) Add and assign.i += 2; // (i = 16) Add-combined assignment.

● What does it mean: "Strings are immutable"?● C# doesn't define a comma-operator.● As we see, C# doesn't provide a delete operator! - Heap memory

is managed automatically by a garbage collector!● Many operators can be overloaded for user defined types in C#.

● We can't define new operators.● We can't modify arity, placement, precedence or associativity of

operators.● The programming language Haskell allows defining new

operators and it allows modifying the precedence andassociativity (together called "fixity" in Haskell) of presentoperators.

● Opinion [NLu]: don't overload operators: it is never required in C#and it is often done wrong, or at least in a questionable way (In C++, overloading of canonical operators is often required for UDTs. -In C# it is only syntactic sugar and not required for a canonicalform of a type.). E.g. the +-operator is overloaded for string to dostring-concatenation. - On the other hand the +-operator meansaddition, which is commutative (one of the minimum requirementsof addition in maths), but string-concatenation is never commutative! (The ,-operator (as sequence operator) would makemore sense for string-concatenation.)

Page 23: (2) c sharp introduction_basics_part_i

23

Logical Operators

● Used to compare values and combine boolean results.

– Comparison: ==, !=, <, >, <=, >=

– Combination: &&, ||, !

– Logical operators return boolean results, not integral results.

● && (logical and) and || (logical or) support short circuit evaluation.

● Logical operators are applied in conditional expressions for control structures (branches and loops).

// The mathematic boolean expression a = b and c = b: // Okif (a == b && c == b) { /* pass */ }// Wrong!if (a && b == c) { /* pass */ }

● What is short circuit evaluation?

Page 24: (2) c sharp introduction_basics_part_i

● What is precedence?● What is associativity? Why is it relevant?

● E.g. if we have a couple of method calls that we combinewith the + operator, we'll have to know which method will becalled first, because the methods could have side effects!

● Rules of the thumb:● Binary operators are generally left associative.● Unary operators, the ternary operator and the assignment

operators are right associative.● What is order of execution? Why is it relevant?

● E.g. if we have an expression like h(g(), f()) or d() * s() howdo we know, which functions are being called first? In C#we know that d() is called before s() is called (left -> right),in the other expression first g() and f() are called and thenh() is called (inner -> outer). It is relevant to know that,because the function calls can have side effects!

● The order of execution is undefined in C++!

24

Precedence, Associativity and Order of Execution

● Precedence and precedence groups.

– Some operators have the same precedence and make up a precedence group.

– As operator priority in maths, precedence is controllable with parentheses.

● Associativity defines evaluation among expressions of the same precedence.

– Associativity is defined as a "direction".

– Associativity is controllable with parentheses as well.

● The order of execution within expressions is strictly defined in C#.

– The order is from left to right and from inner to outer.

int i = 0;Console.WriteLine("{0} {1}", i++, i);// >0 1 → Always this result …// Never 0 0!

Page 25: (2) c sharp introduction_basics_part_i

25

25

Thank you!