SlideShare a Scribd company logo
(2) Introduction of C# Basics – Part I 
Nico Ludwig (@ersatzteilchen) 
● Introductory words: 
● We write programs to solve problems. 
● Now let's inspect a problem that we want to 
solve...
2 
TOC 
● (2) Introduction of C# Basics – Part I 
– A Tour through other .Net Programming Languages 
– C# Syntax Cornerstones
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 "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 be solved 
in everyday language. 
● Now let's inspect how we can solve this problem 
with a program. - We are going to discuss solutions 
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 not 
standardized, HLLs are in opposite hardware 
independent 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 of machine 
(assembly), so they are often not portable.
4 
Visual Basic 10 (VB 10) 
cImports System 
Imports System.IO 
Imports System.Collections.Generic 
Imports System.Text.RegularExpressions 
Module Program 
Sub 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 
Else 
c 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 Sub 
End Module 
● A dialect of the Beginner's All-purpose Symbolic 
Instruction Code (BASIC). - The reputation-problem of 
BASIC programmers: the word "Beginner" in the name of 
the language! 
● VB is a proprietary programming language designed by 
Microsoft. 
● VB 6 was a very productive language (it provided very 
good 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 windows applications 
like MS Excel. 
● This approachability is also due to the fact that VB is 
case-insensitive. - Esp. beginners have often to cope 
with casing of variable and function names, and exactly 
this problem is not present in VB. 
● VB's code is rather noisy as there exist many keywords. 
● Typically VB-only programmers step into the "4GL-trap": 
"IDE, technology, framework and language is all VB!" - 
4GL-developers can't see a difference here, everything is 
integrated.
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 Visual Studio. 
● ECMA: "European Computer Manufacturers 
Association" in past. But meanwhile only the 
acronym "ECMA" or "ECMA International" is used 
to make the international (and no longer european) 
focus clear. 
● C++/CLI (Common Language Infrastructure) is 
Microsoft's C++ variant (extension with some 
syntactical stuff) for .Net programming. Before 
C++/CLI was present, there was "Managed C++" 
for .Net, which is meanwhile deprecated. 
● For the Windows Runtime (WinRT) there exists 
another variant of C++, which is primarily targeted 
to be used with COM to program apps for Windows 
8. - It is called C++/CX (Component Extensions). 
The syntax of C++/CX is similar to the syntax of C+ 
+/CLI, but not all syntactic similar idioms are 
equivalent.
6 
C++/CLI – Part II 
c { 
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); 
} 
} 
}
7 
F# 3 
c#light 
open System 
open System.IO 
open System.Text.RegularExpressions 
if 2 >= Environment.GetCommandLineArgs().Length then 
let 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 very 
compact syntax (in this example), in comparison to the other 
languages being presented. Often examples in F# are "head 
blowing" to show the compactest syntax (this was also done 
deliberately in this example). We can also code F# programs to 
solve 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, but 
whitespace-agnostic syntax has to be used (featuring 
keywords like 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 side 
effect. 
● 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 
the other hand this is rarely required, as F# has great support 
for type inference. 
● Such languages are often used in Artificial Intelligence (AI) and 
the programming of interpreters and compilers, for what F# 
provides special tools. 
● F# is open source. 
● F# can also be used as scripting language.
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 console 
if (0 < args.Length) 
{ 
IDictionary<string, string> latestUpdates = new SortedDictionary<string, string>(); 
Regex parseRex = new Regex(@"[^""]*""(?<appName>[^""]*)""s*((?<versionNo>[^(]*))" ); 
// open and check file, read a line 
foreach (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 
● 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 in 1996. 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 Application Development (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)
9 
C# 5 – Part II 
{ 
latestUpdates.Add(appName, versionNo); 
} 
} 
} 
// output the collected data to console 
foreach (KeyValuePair<string, string> item in latestUpdates) 
{ 
Console.WriteLine("App: {0}, Latest Update: {1}" , item.Key, item.Value); 
} 
} 
} 
}
10 
Common Intermediate Language (CIL, also just IL) 
IL_0001: ldc.i4.1 
IL_0002: newarr System.String 
IL_0007: stloc.s 08 // CS$0$0000 
IL_0009: ldloc.s 08 // CS$0$0000 
IL_000B: ldc.i4.0 
IL_000C: ldstr " C:UsersnludwigDesktopapplication.properties" 
IL_0011: stelem.ref 
IL_0012: ldloc.s 08 // CS$0$0000 
IL_0014: stloc.0 // args 
IL_0015: ldc.i4.0 
IL_0016: ldloc.0 // args 
IL_0017: ldlen 
IL_0018: conv.i4 
IL_0019: clt 
IL_001B: ldc.i4.0 
IL_001C: ceq 
IL_001E: stloc.s 09 // CS$4$0001 
IL_0020: ldloc.s 09 // CS$4$0001 
IL_0022: brtrue IL_0154 
IL_0028: newobj System.Collections.Generic.SortedDictionary<System.String,System.String>..ctor 
IL_002D: stloc.1 // latestUpdates 
IL_002E: ldstr " [^"]*"(?<appName>[^"]*)"s*((?<versionNo>[^(]*))" 
IL_0033: newobj System.Text.RegularExpressions.Regex..ctor 
IL_0038: stloc.2 // parseRex 
IL_003A: ldloc.0 // args 
IL_003B: ldc.i4.0 
IL_003C: ldelem.ref 
IL_003D: call System.IO.File.ReadAllLines 
IL_0042: stloc.s 0A // CS$6$0002 
IL_0044: ldc.i4.0 
IL_0045: stloc.s 0B // CS$7$0003 
IL_0047: br IL_00EF 
IL_004C: ldloc.s 0A // CS$6$0002 
IL_004E: ldloc.s 0B // CS$7$0003 
IL_0050: ldelem.ref 
IL_0051: stloc.3 // aLine 
IL_0053: ldloc.2 // parseRex 
IL_0054: ldloc.3 // aLine 
IL_0055: callvirt System.Text.RegularExpressions.Regex.Match 
IL_005A: stloc.s 04 // match 
IL_005C: ldloc.s 04 // match 
IL_005E: callvirt System.Text.RegularExpressions.Group.get_Success 
IL_0063: ldc.i4.0 
IL_0064: ceq 
IL_0066: stloc.s 09 // CS$4$0001 
IL_0068: ldloc.s 09 // CS$4$0001 
IL_006A: brtrue.s IL_00E8 
IL_006D: ldloc.s 04 // match 
IL_006F: callvirt System.Text.RegularExpressions.Match.get_Groups 
IL_0074: ldstr "appName" 
IL_0079: callvirt System.Text.RegularExpressions.GroupCollection.get_Item 
IL_007E: callvirt System.Object.ToString 
IL_0083: stloc.s 05 // appName 
IL_0085: ldloc.s 04 // match 
IL_0087: callvirt System.Text.RegularExpressions.Match.get_Groups 
IL_008C: ldstr "versionNo" 
IL_0091: callvirt System.Text.RegularExpressions.GroupCollection.get_Item 
IL_0096: callvirt System.Object.ToString 
IL_009B: stloc.s 06 // versionNo 
IL_009D: ldloc.1 // latestUpdates 
IL_009E: ldloc.s 05 // appName 
IL_00A0: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.ContainsKey 
IL_00A5: ldc.i4.0 
IL_00A6: ceq 
IL_00A8: stloc.s 09 // CS$4$0001 
IL_00AA: ldloc.s 09 // CS$4$0001 
IL_00AC: brtrue.s IL_00DA 
IL_00AF: ldc.i4.0 
IL_00B0: ldloc.s 06 // versionNo 
IL_00B2: ldloc.1 // latestUpdates 
IL_00B3: ldloc.s 05 // appName 
IL_00B5: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.get_Item 
IL_00BA: call System.String.CompareOrdinal 
IL_00BF: clt 
IL_00C1: ldc.i4.0 
IL_00C2: ceq 
IL_00C4: stloc.s 09 // CS$4$0001 
IL_00C6: ldloc.s 09 // CS$4$0001 
IL_00C8: brtrue.s IL_00D7 
IL_00CB: ldloc.1 // latestUpdates 
IL_00CC: ldloc.s 05 // appName 
IL_00CE: ldloc.s 06 // versionNo 
IL_00D0: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.set_Item 
IL_00D8: br.s IL_00E7 
IL_00DB: ldloc.1 // latestUpdates 
IL_00DC: ldloc.s 05 // appName 
IL_00DE: ldloc.s 06 // versionNo 
IL_00E0: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.Add 
IL_00E9: ldloc.s 0B // CS$7$0003 
IL_00EB: ldc.i4.1 
IL_00EC: add 
IL_00ED: stloc.s 0B // CS$7$0003 
IL_00EF: ldloc.s 0B // CS$7$0003 
IL_00F1: ldloc.s 0A // CS$6$0002 
IL_00F3: ldlen 
IL_00F4: conv.i4 
IL_00F5: clt 
IL_00F7: stloc.s 09 // CS$4$0001 
IL_00F9: ldloc.s 09 // CS$4$0001 
IL_00FB: brtrue IL_004C 
IL_0101: ldloc.1 // latestUpdates 
IL_0102: callvirt System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.String>>.GetEnumerator 
IL_0107: stloc.s 0C // CS$5$0004 
IL_0109: br.s IL_012F 
IL_010B: ldloc.s 0C // CS$5$0004 
IL_010D: callvirt System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<System.String,System.String>>.get_Current 
IL_0112: stloc.s 07 // item 
IL_0115: ldstr "App: {0}, Latest Update: {1}" 
IL_011A: ldloca.s 07 // item 
IL_011C: call System.Collections.Generic.KeyValuePair<System.String,System.String>.get_Key 
IL_0121: ldloca.s 07 // item 
IL_0123: call System.Collections.Generic.KeyValuePair<System.String,System.String>.get_Value 
IL_0128: call System.Console.WriteLine 
IL_012F: ldloc.s 0C // CS$5$0004 
IL_0131: callvirt System.Collections.IEnumerator.MoveNext 
IL_0136: stloc.s 09 // CS$4$0001 
IL_0138: ldloc.s 09 // CS$4$0001 
IL_013A: brtrue.s IL_010B 
IL_013C: leave.s IL_0152 
IL_013E: ldloc.s 0C // CS$5$0004 
IL_0140: ldnull 
IL_0141: ceq 
IL_0143: stloc.s 09 // CS$4$0001 
IL_0145: ldloc.s 09 // CS$4$0001 
IL_0147: brtrue.s IL_0151 
IL_0149: ldloc.s 0C // CS$5$0004 
IL_014B: callvirt System.IDisposable.Dispose 
IL_0151: endfinally 
● IL is the very low level language specified by the 
CLI. 
● This piece of IL was generated from C# 5 code. It 
was generated in debug mode, which generates 
nop op-codes, which makes debugging easier and 
line numbers. The nops have been removed. 
● IL is a platform independent, object oriented and 
stack-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-called 
bytecode. The result is a CLI assembly. 
● During run time the bytecode will be translated 
into native machine code (by a JIT compiler of the 
native runtime) and then it will be executed.
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 Manufacturers 
Association" in past. But meanwhile only the 
acronym "ECMA" or "ECMA International" is used to 
make the international (and no longer european) 
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".
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 good 
documentation available as well as some IDEs. 
● MS Visual Studio (the Express edition is free) 
● #develop (free)
● 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 
13 
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 with semicolons. 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.cs 
using 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!"); 
} 
} 
}
14 
Code Snippets 
● Hence we'll begin using snippets as code examples, i.e. no Main() etc.! 
// Program.cs 
using System; 
namespace ConsoleApplication 
{ 
public class Program 
{ 
public static void Main(string[] args) 
{ 
Console.WriteLine("Hello World!"); 
} 
} 
} 
Console.WriteLine("Hello World!"); 
● In the end no fully runnable program code will be shown in upcoming lectures!
int count = 2; 
count = 2; 
int zero = 0; 
int oddResult = 42/zero; 
● What keywords do you know from any programming 
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? 
● The time during programming is often called 
"design time". 
● (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.
16 
C# Syntax Cornerstones – Part I – Imperative Elements 
if (answerIsOk) { 
Console.WriteLine("Result: "+(3 + 4)); 
} 
● 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. 
int age = 19; 
age = 25; 
double width = 32.8; 
● In C# multiple variables of the same type can be 
defined/declared in one statement.
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: 
// Conversion with cast: 
int i = (int)2.78; 
– 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 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 for primitive 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 for 
comparisons (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 that conversion 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 into byte, so a 
part of 300 will overflow (the most significant bits of the result will be discarded) and 44 will make up the result of b. With 
the expression checked((byte)(b + 200)), this overflow wouldn't happen, instead an OverflowException would be thrown! 
Often overflows are errors (but sometimes it is part of the algorithm, e.g. for hash calculation). The keyword checked will 
replace overflowing operators with throwing ones (add -> add.ovf in this 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 new VS project. 
● Only integral and the decimal will overflow, other floating point types can handle infinity.
18 
C# Syntax Cornerstones – Part III – Identifiers and 
Comments 
• 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! 
/* commented */ /** commented */ // commented /// commented (triple slash) 
• 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#.
19 
Operator Notations – Arity 
● Binary operators 
// Addition as binary operator: 
int sum = 2 + 3; 
● Unary operators 
// Increment as unary operator: 
int i = 1; 
++i; // Increments i (the result is 2). 
● Ternary operator 
// 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 -> useful in 
loops! 
● Apple's Swift programming language guide 
does explicitly suggest to use prefix 
increment/decrement by default, unless the 
specific behavior of the postfix variants is 
required. (This could be understood like Apple 
counts prefix increment/decrement as "primary 
operator".) 
● What are ternary operators? 
● The decision operator ?: (sometimes we call it 
"Elvis operator").
20 
Operator Notations – Placement 
● Prefix operators 
// Negation as prefix operator: 
bool succeeded = !failed; 
● Postfix operators 
// Increment as postfix operator: 
int result = item++; 
● Infix operators 
// Addition as infix operator: 
int sum = 2 + 3;
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 an 
integer 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?
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: => 
int i = 12; 
i = i + 2; // (i = 14) Add and assign. 
i += 2; // (i = 16) Add-combined assignment. 
● C# permits to redefine (overload) operators for user defined types UDT. 
● 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 and associativity (together 
called "fixity" in Haskell) of present operators. 
● 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 canonical form of a 
type.). E.g. the +-operator is overloaded for string to do string-concatenation. 
- On the other hand the +-operator means addition, 
which is commutative (one of the minimum requirements of addition 
in maths), but string-concatenation is never commutative! (The 
,-operator (as sequence operator) would make more sense for string-concatenation.)
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. 
// The mathematic boolean expression a = b and c = b: 
// Ok 
if (a == b && c == b) { /* pass */ } 
// Wrong! 
if (a && b == c) { /* pass */ } 
● Logical operators are applied in conditional expressions for control structures (branches and loops). 
● What is short circuit evaluation?
● What is precedence? 
● What is associativity? Why is it relevant? 
● E.g. if we have a couple of method calls that we combine with 
the + operator, we'll have to know which method will be called 
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() how do 
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 then h() 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!
25 
25 
Thank you!

More Related Content

PPT
project introduction
PPT
Visual Studio .NET2010
PPTX
C compilation process
PDF
.Net passé, présent et futur
PPTX
Namespaces in C#
PDF
The compilation process
PPT
Compilation
PDF
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
project introduction
Visual Studio .NET2010
C compilation process
.Net passé, présent et futur
Namespaces in C#
The compilation process
Compilation
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH

What's hot (20)

DOCX
Srgoc dotnet_new
PPTX
File handling With Solve Programs
PPTX
Linker and loader upload
PPTX
C++ basics
PDF
Architecting the Future: Abstractions and Metadata - KCDC
PDF
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
PPTX
Compilation of c
PPTX
Python Streaming Pipelines with Beam on Flink
PDF
An introduction on language processing
PPTX
C++ in Action Webinar: Move your C++ projects to C++Builder 10 Seattle
PDF
Web programming UNIT II by Bhavsingh Maloth
PDF
Architecting the Future: Abstractions and Metadata - CodeStock
PPT
C introduction
PPTX
.NET and C# introduction
ODP
LD_PRELOAD Exploitation - DC9723
PDF
Flink Forward Berlin 2018: Robert Bradshaw & Maximilian Michels - "Universal ...
PDF
Analysis of merge requests in GitLab using PVS-Studio for C#
PDF
The why and how of moving to php 7
PDF
Dynamic Linker
PDF
Fast and Reliable Swift APIs with gRPC
Srgoc dotnet_new
File handling With Solve Programs
Linker and loader upload
C++ basics
Architecting the Future: Abstractions and Metadata - KCDC
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
Compilation of c
Python Streaming Pipelines with Beam on Flink
An introduction on language processing
C++ in Action Webinar: Move your C++ projects to C++Builder 10 Seattle
Web programming UNIT II by Bhavsingh Maloth
Architecting the Future: Abstractions and Metadata - CodeStock
C introduction
.NET and C# introduction
LD_PRELOAD Exploitation - DC9723
Flink Forward Berlin 2018: Robert Bradshaw & Maximilian Michels - "Universal ...
Analysis of merge requests in GitLab using PVS-Studio for C#
The why and how of moving to php 7
Dynamic Linker
Fast and Reliable Swift APIs with gRPC
Ad

Viewers also liked (20)

PPTX
Siroh uts-perang khaibar
PPTX
Lecture1 classes4
PPTX
Academy versus the pew
PPTX
View from the classroom window
PPT
Currículo de Castilla la mancha.
PPT
Sign up for free music
PDF
News Psicopedagogicos
PPT
Filosofia de la ciencia2
PDF
Flyer 2
PPTX
กระบวนการโครงงาน
PPT
Sharing music downloads
PPT
070901 1706 files
PPTX
Fase+planificación+grupo d
PPSX
Presentación Casa rural Asturias
PPT
Ten Aragon Slide Show
PPT
2011.10.25 WFM Council Meeting ICC Panel on the Libya Question
DOC
If I Could Not Fail, I Would..
DOCX
Digital Photo#4 Mode Selector
PPTX
Resumen Temas Estudiados #1
PDF
Los canes 2
Siroh uts-perang khaibar
Lecture1 classes4
Academy versus the pew
View from the classroom window
Currículo de Castilla la mancha.
Sign up for free music
News Psicopedagogicos
Filosofia de la ciencia2
Flyer 2
กระบวนการโครงงาน
Sharing music downloads
070901 1706 files
Fase+planificación+grupo d
Presentación Casa rural Asturias
Ten Aragon Slide Show
2011.10.25 WFM Council Meeting ICC Panel on the Libya Question
If I Could Not Fail, I Would..
Digital Photo#4 Mode Selector
Resumen Temas Estudiados #1
Los canes 2
Ad

Similar to (1) c sharp introduction_basics_dot_net (20)

PDF
(2) c sharp introduction_basics_part_i
ODP
(2) c sharp introduction_basics_part_i
ODP
(1) c sharp introduction_basics_dot_net
PPT
PDF
(1) cpp introducing the_cpp_programming_language
PPT
C# Fundamental
PPT
Trends in Programming Technology you might want to keep an eye on af Bent Tho...
PPTX
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PPTX
How To Code in C#
PDF
Intro to .NET and Core C#
PPTX
Introduction to C#
PDF
Understanding C# in .NET
PPTX
C# .NET - Um overview da linguagem
PDF
C C For Beginners Crash Course Master C Programming Fast And Easy Today Compu...
PPTX
C c#
PPTX
01. Introduction to Programming
PDF
How to build the Web
PDF
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
PPT
Tutorial csharp
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
(1) c sharp introduction_basics_dot_net
(1) cpp introducing the_cpp_programming_language
C# Fundamental
Trends in Programming Technology you might want to keep an eye on af Bent Tho...
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
How To Code in C#
Intro to .NET and Core C#
Introduction to C#
Understanding C# in .NET
C# .NET - Um overview da linguagem
C C For Beginners Crash Course Master C Programming Fast And Easy Today Compu...
C c#
01. Introduction to Programming
How to build the Web
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
Tutorial csharp

More from Nico Ludwig (20)

PPTX
Grundkurs fuer excel_part_v
PPTX
Grundkurs fuer excel_part_iv
PPTX
Grundkurs fuer excel_part_iii
PPTX
Grundkurs fuer excel_part_ii
PPTX
Grundkurs fuer excel_part_i
PDF
(2) gui drawing
ODP
(2) gui drawing
PDF
(1) gui history_of_interactivity
ODP
(1) gui history_of_interactivity
PDF
New c sharp4_features_part_vi
PDF
New c sharp4_features_part_v
PDF
New c sharp4_features_part_iv
ODP
New c sharp4_features_part_iii
PDF
New c sharp4_features_part_ii
PDF
New c sharp4_features_part_i
PDF
New c sharp3_features_(linq)_part_v
PDF
New c sharp3_features_(linq)_part_iv
ODP
New c sharp3_features_(linq)_part_iv
PDF
New c sharp3_features_(linq)_part_iii
PDF
New c sharp3_features_(linq)_part_ii
Grundkurs fuer excel_part_v
Grundkurs fuer excel_part_iv
Grundkurs fuer excel_part_iii
Grundkurs fuer excel_part_ii
Grundkurs fuer excel_part_i
(2) gui drawing
(2) gui drawing
(1) gui history_of_interactivity
(1) gui history_of_interactivity
New c sharp4_features_part_vi
New c sharp4_features_part_v
New c sharp4_features_part_iv
New c sharp4_features_part_iii
New c sharp4_features_part_ii
New c sharp4_features_part_i
New c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_ii

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Encapsulation theory and applications.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPT
Teaching material agriculture food technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Machine learning based COVID-19 study performance prediction
PDF
Electronic commerce courselecture one. Pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
cuic standard and advanced reporting.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
KodekX | Application Modernization Development
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
20250228 LYD VKU AI Blended-Learning.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Chapter 3 Spatial Domain Image Processing.pdf
Review of recent advances in non-invasive hemoglobin estimation
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation theory and applications.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Reach Out and Touch Someone: Haptics and Empathic Computing
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Teaching material agriculture food technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Machine learning based COVID-19 study performance prediction
Electronic commerce courselecture one. Pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
cuic standard and advanced reporting.pdf
Encapsulation_ Review paper, used for researhc scholars
KodekX | Application Modernization Development
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

(1) c sharp introduction_basics_dot_net

  • 1. (2) Introduction of C# Basics – Part I Nico Ludwig (@ersatzteilchen) ● Introductory words: ● We write programs to solve problems. ● Now let's inspect a problem that we want to solve...
  • 2. 2 TOC ● (2) Introduction of C# Basics – Part I – A Tour through other .Net Programming Languages – C# Syntax Cornerstones
  • 3. 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 "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 be solved in everyday language. ● Now let's inspect how we can solve this problem with a program. - We are going to discuss solutions 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 not standardized, HLLs are in opposite hardware independent 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 of machine (assembly), so they are often not portable.
  • 4. 4 Visual Basic 10 (VB 10) cImports System Imports System.IO Imports System.Collections.Generic Imports System.Text.RegularExpressions Module Program Sub 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 Else c 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 Sub End Module ● A dialect of the Beginner's All-purpose Symbolic Instruction Code (BASIC). - The reputation-problem of BASIC programmers: the word "Beginner" in the name of the language! ● VB is a proprietary programming language designed by Microsoft. ● VB 6 was a very productive language (it provided very good 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 windows applications like MS Excel. ● This approachability is also due to the fact that VB is case-insensitive. - Esp. beginners have often to cope with casing of variable and function names, and exactly this problem is not present in VB. ● VB's code is rather noisy as there exist many keywords. ● Typically VB-only programmers step into the "4GL-trap": "IDE, technology, framework and language is all VB!" - 4GL-developers can't see a difference here, everything is integrated.
  • 5. 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 Visual Studio. ● ECMA: "European Computer Manufacturers Association" in past. But meanwhile only the acronym "ECMA" or "ECMA International" is used to make the international (and no longer european) focus clear. ● C++/CLI (Common Language Infrastructure) is Microsoft's C++ variant (extension with some syntactical stuff) for .Net programming. Before C++/CLI was present, there was "Managed C++" for .Net, which is meanwhile deprecated. ● For the Windows Runtime (WinRT) there exists another variant of C++, which is primarily targeted to be used with COM to program apps for Windows 8. - It is called C++/CX (Component Extensions). The syntax of C++/CX is similar to the syntax of C+ +/CLI, but not all syntactic similar idioms are equivalent.
  • 6. 6 C++/CLI – Part II c { 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); } } }
  • 7. 7 F# 3 c#light open System open System.IO open System.Text.RegularExpressions if 2 >= Environment.GetCommandLineArgs().Length then let 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 very compact syntax (in this example), in comparison to the other languages being presented. Often examples in F# are "head blowing" to show the compactest syntax (this was also done deliberately in this example). We can also code F# programs to solve 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, but whitespace-agnostic syntax has to be used (featuring keywords like 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 side effect. ● 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 the other hand this is rarely required, as F# has great support for type inference. ● Such languages are often used in Artificial Intelligence (AI) and the programming of interpreters and compilers, for what F# provides special tools. ● F# is open source. ● F# can also be used as scripting language.
  • 8. 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 console if (0 < args.Length) { IDictionary<string, string> latestUpdates = new SortedDictionary<string, string>(); Regex parseRex = new Regex(@"[^""]*""(?<appName>[^""]*)""s*((?<versionNo>[^(]*))" ); // open and check file, read a line foreach (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 ● 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 in 1996. 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 Application Development (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)
  • 9. 9 C# 5 – Part II { latestUpdates.Add(appName, versionNo); } } } // output the collected data to console foreach (KeyValuePair<string, string> item in latestUpdates) { Console.WriteLine("App: {0}, Latest Update: {1}" , item.Key, item.Value); } } } }
  • 10. 10 Common Intermediate Language (CIL, also just IL) IL_0001: ldc.i4.1 IL_0002: newarr System.String IL_0007: stloc.s 08 // CS$0$0000 IL_0009: ldloc.s 08 // CS$0$0000 IL_000B: ldc.i4.0 IL_000C: ldstr " C:UsersnludwigDesktopapplication.properties" IL_0011: stelem.ref IL_0012: ldloc.s 08 // CS$0$0000 IL_0014: stloc.0 // args IL_0015: ldc.i4.0 IL_0016: ldloc.0 // args IL_0017: ldlen IL_0018: conv.i4 IL_0019: clt IL_001B: ldc.i4.0 IL_001C: ceq IL_001E: stloc.s 09 // CS$4$0001 IL_0020: ldloc.s 09 // CS$4$0001 IL_0022: brtrue IL_0154 IL_0028: newobj System.Collections.Generic.SortedDictionary<System.String,System.String>..ctor IL_002D: stloc.1 // latestUpdates IL_002E: ldstr " [^"]*"(?<appName>[^"]*)"s*((?<versionNo>[^(]*))" IL_0033: newobj System.Text.RegularExpressions.Regex..ctor IL_0038: stloc.2 // parseRex IL_003A: ldloc.0 // args IL_003B: ldc.i4.0 IL_003C: ldelem.ref IL_003D: call System.IO.File.ReadAllLines IL_0042: stloc.s 0A // CS$6$0002 IL_0044: ldc.i4.0 IL_0045: stloc.s 0B // CS$7$0003 IL_0047: br IL_00EF IL_004C: ldloc.s 0A // CS$6$0002 IL_004E: ldloc.s 0B // CS$7$0003 IL_0050: ldelem.ref IL_0051: stloc.3 // aLine IL_0053: ldloc.2 // parseRex IL_0054: ldloc.3 // aLine IL_0055: callvirt System.Text.RegularExpressions.Regex.Match IL_005A: stloc.s 04 // match IL_005C: ldloc.s 04 // match IL_005E: callvirt System.Text.RegularExpressions.Group.get_Success IL_0063: ldc.i4.0 IL_0064: ceq IL_0066: stloc.s 09 // CS$4$0001 IL_0068: ldloc.s 09 // CS$4$0001 IL_006A: brtrue.s IL_00E8 IL_006D: ldloc.s 04 // match IL_006F: callvirt System.Text.RegularExpressions.Match.get_Groups IL_0074: ldstr "appName" IL_0079: callvirt System.Text.RegularExpressions.GroupCollection.get_Item IL_007E: callvirt System.Object.ToString IL_0083: stloc.s 05 // appName IL_0085: ldloc.s 04 // match IL_0087: callvirt System.Text.RegularExpressions.Match.get_Groups IL_008C: ldstr "versionNo" IL_0091: callvirt System.Text.RegularExpressions.GroupCollection.get_Item IL_0096: callvirt System.Object.ToString IL_009B: stloc.s 06 // versionNo IL_009D: ldloc.1 // latestUpdates IL_009E: ldloc.s 05 // appName IL_00A0: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.ContainsKey IL_00A5: ldc.i4.0 IL_00A6: ceq IL_00A8: stloc.s 09 // CS$4$0001 IL_00AA: ldloc.s 09 // CS$4$0001 IL_00AC: brtrue.s IL_00DA IL_00AF: ldc.i4.0 IL_00B0: ldloc.s 06 // versionNo IL_00B2: ldloc.1 // latestUpdates IL_00B3: ldloc.s 05 // appName IL_00B5: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.get_Item IL_00BA: call System.String.CompareOrdinal IL_00BF: clt IL_00C1: ldc.i4.0 IL_00C2: ceq IL_00C4: stloc.s 09 // CS$4$0001 IL_00C6: ldloc.s 09 // CS$4$0001 IL_00C8: brtrue.s IL_00D7 IL_00CB: ldloc.1 // latestUpdates IL_00CC: ldloc.s 05 // appName IL_00CE: ldloc.s 06 // versionNo IL_00D0: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.set_Item IL_00D8: br.s IL_00E7 IL_00DB: ldloc.1 // latestUpdates IL_00DC: ldloc.s 05 // appName IL_00DE: ldloc.s 06 // versionNo IL_00E0: callvirt System.Collections.Generic.IDictionary<System.String,System.String>.Add IL_00E9: ldloc.s 0B // CS$7$0003 IL_00EB: ldc.i4.1 IL_00EC: add IL_00ED: stloc.s 0B // CS$7$0003 IL_00EF: ldloc.s 0B // CS$7$0003 IL_00F1: ldloc.s 0A // CS$6$0002 IL_00F3: ldlen IL_00F4: conv.i4 IL_00F5: clt IL_00F7: stloc.s 09 // CS$4$0001 IL_00F9: ldloc.s 09 // CS$4$0001 IL_00FB: brtrue IL_004C IL_0101: ldloc.1 // latestUpdates IL_0102: callvirt System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.String>>.GetEnumerator IL_0107: stloc.s 0C // CS$5$0004 IL_0109: br.s IL_012F IL_010B: ldloc.s 0C // CS$5$0004 IL_010D: callvirt System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<System.String,System.String>>.get_Current IL_0112: stloc.s 07 // item IL_0115: ldstr "App: {0}, Latest Update: {1}" IL_011A: ldloca.s 07 // item IL_011C: call System.Collections.Generic.KeyValuePair<System.String,System.String>.get_Key IL_0121: ldloca.s 07 // item IL_0123: call System.Collections.Generic.KeyValuePair<System.String,System.String>.get_Value IL_0128: call System.Console.WriteLine IL_012F: ldloc.s 0C // CS$5$0004 IL_0131: callvirt System.Collections.IEnumerator.MoveNext IL_0136: stloc.s 09 // CS$4$0001 IL_0138: ldloc.s 09 // CS$4$0001 IL_013A: brtrue.s IL_010B IL_013C: leave.s IL_0152 IL_013E: ldloc.s 0C // CS$5$0004 IL_0140: ldnull IL_0141: ceq IL_0143: stloc.s 09 // CS$4$0001 IL_0145: ldloc.s 09 // CS$4$0001 IL_0147: brtrue.s IL_0151 IL_0149: ldloc.s 0C // CS$5$0004 IL_014B: callvirt System.IDisposable.Dispose IL_0151: endfinally ● IL is the very low level language specified by the CLI. ● This piece of IL was generated from C# 5 code. It was generated in debug mode, which generates nop op-codes, which makes debugging easier and line numbers. The nops have been removed. ● IL is a platform independent, object oriented and stack-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-called bytecode. The result is a CLI assembly. ● During run time the bytecode will be translated into native machine code (by a JIT compiler of the native runtime) and then it will be executed.
  • 11. 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 Manufacturers Association" in past. But meanwhile only the acronym "ECMA" or "ECMA International" is used to make the international (and no longer european) 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".
  • 12. 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 good documentation available as well as some IDEs. ● MS Visual Studio (the Express edition is free) ● #develop (free)
  • 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 13 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 with semicolons. 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.cs using 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!"); } } }
  • 14. 14 Code Snippets ● Hence we'll begin using snippets as code examples, i.e. no Main() etc.! // Program.cs using System; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } Console.WriteLine("Hello World!"); ● In the end no fully runnable program code will be shown in upcoming lectures!
  • 15. int count = 2; count = 2; int zero = 0; int oddResult = 42/zero; ● What keywords do you know from any programming 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? ● The time during programming is often called "design time". ● (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.
  • 16. 16 C# Syntax Cornerstones – Part I – Imperative Elements if (answerIsOk) { Console.WriteLine("Result: "+(3 + 4)); } ● 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. int age = 19; age = 25; double width = 32.8; ● In C# multiple variables of the same type can be defined/declared in one statement.
  • 17. 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: // Conversion with cast: int i = (int)2.78; – 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 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 for primitive 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 for comparisons (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 that conversion 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 into byte, so a part of 300 will overflow (the most significant bits of the result will be discarded) and 44 will make up the result of b. With the expression checked((byte)(b + 200)), this overflow wouldn't happen, instead an OverflowException would be thrown! Often overflows are errors (but sometimes it is part of the algorithm, e.g. for hash calculation). The keyword checked will replace overflowing operators with throwing ones (add -> add.ovf in this 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 new VS project. ● Only integral and the decimal will overflow, other floating point types can handle infinity.
  • 18. 18 C# Syntax Cornerstones – Part III – Identifiers and Comments • 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! /* commented */ /** commented */ // commented /// commented (triple slash) • 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#.
  • 19. 19 Operator Notations – Arity ● Binary operators // Addition as binary operator: int sum = 2 + 3; ● Unary operators // Increment as unary operator: int i = 1; ++i; // Increments i (the result is 2). ● Ternary operator // 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 -> useful in loops! ● Apple's Swift programming language guide does explicitly suggest to use prefix increment/decrement by default, unless the specific behavior of the postfix variants is required. (This could be understood like Apple counts prefix increment/decrement as "primary operator".) ● What are ternary operators? ● The decision operator ?: (sometimes we call it "Elvis operator").
  • 20. 20 Operator Notations – Placement ● Prefix operators // Negation as prefix operator: bool succeeded = !failed; ● Postfix operators // Increment as postfix operator: int result = item++; ● Infix operators // Addition as infix operator: int sum = 2 + 3;
  • 21. 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 an integer 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?
  • 22. 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: => int i = 12; i = i + 2; // (i = 14) Add and assign. i += 2; // (i = 16) Add-combined assignment. ● C# permits to redefine (overload) operators for user defined types UDT. ● 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 and associativity (together called "fixity" in Haskell) of present operators. ● 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 canonical form of a type.). E.g. the +-operator is overloaded for string to do string-concatenation. - On the other hand the +-operator means addition, which is commutative (one of the minimum requirements of addition in maths), but string-concatenation is never commutative! (The ,-operator (as sequence operator) would make more sense for string-concatenation.)
  • 23. 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. // The mathematic boolean expression a = b and c = b: // Ok if (a == b && c == b) { /* pass */ } // Wrong! if (a && b == c) { /* pass */ } ● Logical operators are applied in conditional expressions for control structures (branches and loops). ● What is short circuit evaluation?
  • 24. ● What is precedence? ● What is associativity? Why is it relevant? ● E.g. if we have a couple of method calls that we combine with the + operator, we'll have to know which method will be called 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() how do 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 then h() 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!
  • 25. 25 25 Thank you!