This document summarizes and compares several programming languages - C#, Visual Basic, F#, C++/CLI, and the common intermediate language (CIL) - by providing concise code examples and explanations of each language.
1. ● 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
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)
2009-04-06 12:44:34 +0200: Installed "iMovie Update" (8)
2009-07-30 13:11:28 +0200: Installed "iMovie Update" (8)
2009-04-06 12:43:31 +0200: Installed "iTunes" (8)
…
● 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)
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)
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)
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. 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 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.!
● In the end no fully runnable program code will be shown in upcoming lectures!
// Program.cs
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Console.WriteLine("Hello World!");
15. ● 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.
int count = 2;
count = 2;
int zero = 0;
int oddResult = 42/zero;
16. 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 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:
– 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 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!
• 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)
19. 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 -> 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
● 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;
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: =>
● 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 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.
● Logical operators are applied in conditional expressions for control structures (branches and loops).
// The mathematic boolean expression a = b and c = b:
// Ok
if (a == b && c == b) { /* pass */ }
// Wrong!
if (a && b == c) { /* pass */ }
● 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!