16
1 Nico Ludwig (@ersatzteilchen) (3) Introduction of C# Basics – Part II

(3) c sharp introduction_basics_part_ii

Embed Size (px)

DESCRIPTION

- C# Syntax Cornerstones

Citation preview

Page 1: (3) c sharp introduction_basics_part_ii

1

Nico Ludwig (@ersatzteilchen)

(3) Introduction of C# Basics – Part II

Page 2: (3) c sharp introduction_basics_part_ii

2

TOC

● (3) Introduction of C# Basics – Part II

– C# Syntax Cornerstones

Page 3: (3) c sharp introduction_basics_part_ii

3

Control Structures – Expressions, Statements and Blocks

● An expression is like a mathematical term: "something that yields a value".

● A statement is a set of expressions to take effect, it doesn't need to yield a value.

– Single statements need to be terminated with a semicolon.

● A block is a set of statements withing curly braces ({}).

– C# code is written in blocks, this is a main style feature.

● Blocks fringe type and member functions bodies and scopes.

– Blocks must be cascaded to code meaningful programs.

– Blocks should be indented to enhance readability!

– Use common conventions for indenting and bracing!

● Blocks are also used for control structures and special contexts.

if (true) // BSD style{

// In the block.}

if (true) { // 1TBS styleif (true) {

// In the cascaded// if-block.

}}

● Expressions and statements are basically the same as in C/C++:● An expression is like a mathematical term: "something, that yields a value".● A statement is a set of expressions to take effect, it has not to yield a value. Single

statements need to be terminated with a semicolon.● Multiple statements can be written in one line, but need to be terminated with

semicolons each.● C# code is written in blocks.● Blocks:

● It is absolutely required to indent cascading blocks to make the code readable!● What is a scope?

● A scope defines an area of code, in which a variable has certain meaning and canbe used.

● Other example: The scope of a variables in JavaScript is the scope of the function,in which the variable is defined. - There are no other sub scopes (e.g. curly braces).

● Bracing styles:● BSD (Berkley Software Distribution) style: should generally be used, when beginning

programing, as it has a very good readability.● 1TSB style: "Only true bracing style" It is used on the slides, as this style saves some

lines (it is a "line-saver" style). This style is often used in Java code. It is the only styleallowing to write correct JavaScript code to avoid mistakes because of semicoloninsertion.

● There exist many more bracing styles, which is often a source of coding wars amongprogrammers, therefor we need coding conventions to cool down the minds.

● Important special contexts: using and lock.● Within blocks we can use a free syntax in C#, but please adhere to some coding

conventions.

Page 4: (3) c sharp introduction_basics_part_ii

4

Control Structures – Conditional Branching

● if/else statements

– Execute code, if a specified condition is met.

– Condition has to evaluate to bool, integers are no bools!

– Can be cascaded, but combining conditions via logical operators is preferred.

– Each conditional code should be in a block!

– Alternatively use the ?: operator.

● switch statement

– Does switch among a set of branched code blocks.

– Compares the statement's input against a set of constants.

– These constants can be integral values (int, long, enum) and even strings!

– Uses gotos, fall throughs, breaks and defaults - it is rather complicated to use!

– Good, when used with only returns instead of any breaks in the case sections.

● According to if/else:● Integers will not be interpreted as bools, i.e. 0 won't be interpreted

as false! - There is no "freely"evaluation of values for "falsyness" and "truthyness" like in C/C++.

● We'll always use blocks! Matching if/else pairs are clear to thereader when we use blocks. This avoids the “dangling else”problem.

● The operator ?: is more difficult to debug, because it does not consistof alternative statements to be executed.

● According to switch:● Can be used with strings, which is a little bit faster than if/else chains

(string interning), but this should not be a cause to use it, though. ● Floating point values cannot be used.● (In C/C++ only allowed with integral types. In Java we can also useStrings.)

● In C# switch statements need braces surrounding all cases and thedefault-case needs a break statement (in opposite to C/C++).

● (Opinion of [NLu]: Don't use switch! It looks temptingly simple, but israther unstructured. Also it leads to longer methods. It should beused only in the most low level code.)

Page 5: (3) c sharp introduction_basics_part_ii

5

Control Structures – Unconditional Branching

● return and throw

– Return from a member function with or w/o value.

– Throw an exception, which leaves a member function as well.

● labels and goto

– The unconditional jump statement.

– Do not use goto statements! Leads to "pasta oriented programming".

– When is goto used anyhow:

● On automatic generation of code.

● For algorithms that need to run really fast.

● yield return and yield break

– Advanced loop control with iterators (i.e. to support IEnumerable/<T>).

– Important for .Net 3.5/C#3 and greater (Language INtegrated Query (LINQ)).

● According goto: ● Don't use gotos in general. Exception: to

escape from the innermost loop of a couple ofcascaded loops a goto may be appropriate.

● We can not jump behind a declaration/initialization of a variable:

goto lab; // Invalid!int c = 42;lab:

Console.WriteLine(c);

Page 6: (3) c sharp introduction_basics_part_ii

6

Control Structures – Iteration – for Loop

● The for loop is a flexible counting head controlled loop statement.

– 1. Initialization expression or statement.

– 2. Conditional expression

– 3. Update expression.

● Can imitate the functionality of any other loop!

● => Popular to iterate arrays (filling, processing and output).

● Loops are executed sequentially, not in parallel (e.g. on multiple CPU cores).

int array[] = {1, 2, 3, 4, 5};for (int i = 0; 5 > i; ++i) {

Console.WriteLine(array[i]);}

● The for loop is flexible:● All parts of for's head are optional.● If a counter variable is defined in for's head this

variable is only valid/known in the for block (this isthe variable's scope).● How can we extend the counter variable's

scope?● What kinds of update expressions do you know?

● Arrays: The for loop can provide a counter variablethat can be used as index for arrays.● Arrays will be discussed later in this presentation.

● Downside of the for loop: the pieces/statements offor's definition are not executed in the order they arewritten, which makes it difficult to understand forbeginners.

Page 7: (3) c sharp introduction_basics_part_ii

7

Control Structures – Iteration – foreach Loop

● Iteration of "IEnumerable/<T>" Collections.

– The .Net Collection types and intrinsic arrays are IEnumerable/<T> types.

– I.e. these types implement the interface IEnumerable/<T>.

● In principle a pure "read" loop, i.e. a loop with some constraints:

– We can not assign the item variable.

– We can not modify the iterated Collection.

● Comfortable with IEnumerable/<T> types.

– (For the time being, foreach should not be used in this course (we'll use for loops instead).)

– We should use them, if we don't know the length of the Collection we're iterating...

– ... comfortable with LINQ sequences in C#3 and greater.

– Extra benefit: For each loops are good to avoid off-by-one errors: there is no index.

– The type IEnumerable/<T> and the keywords yield/foreach work together.

int array[] = {1, 2, 3, 4, 5};foreach (int item in array) {

Console.WriteLine(item);}

● Basically the foreach loop is simpler than the for loop, because we need less statements toexpress it. Also do we not need to care about theend condition.

● (Opinion of [NLu]: At least when beginningprogramming in C# the for loop should bepreferred. Having more experience, foreach loopscan be used to exploit their convenience.)

Page 8: (3) c sharp introduction_basics_part_ii

8

Control Structures – Iteration – while and do Loop

● while loops are head controlled.

● do loops are foot controlled.

– Must be used with a block!

– Useful for menus at the console.

● Normally, the update-operation of the loop condition is done in the loop's body.

● Loops are executed sequentially, not in parallel (e.g. on multiple CPU cores).

int array[] = {1, 2, 3, 4, 5};int i = 0;while (i < 5) {

Console.WriteLine(array[i]);++i;

}

int array[] = {1, 2, 3, 4, 5};int i = 0;do {

Console.WriteLine(array[i]);++i;

} while (i < 5);

● In which situations is the update of the loopcondition not required within the loop?● If we have a side effect in the conditional

expression in the head or foot (e.g. ++i).● If the data that is checked in the loop condition

will be somehow modified from "outside" (e.g.from different threads).

● Using only control structures w/o unconditionalbranching with gotos is called "structuredprogramming".

Page 9: (3) c sharp introduction_basics_part_ii

9

Control Structures – Iteration – Loop Control

● continue – skips the current loop.

● break – leaves the next surrounding loop completely.

● goto – jumps to a label at almost any position in code.

– Can be used to leave a nested loop.

● return and throw – leave a member function.

● yield return and yield break – control iterator generation from loop.

Page 10: (3) c sharp introduction_basics_part_ii

10

Control Structures – Handling Exceptions

● The .Net way to handle run time errors in a structured way.

● Control flow with the keywords try, catch and finally.

– Must be used with blocks!

● Must be understood by .Net programmers!

– Exceptions are used very often in .Net code.

– Combines the ideas of if and return somewhat.

● Exception handling will be discussed in a futurelecture.

Page 11: (3) c sharp introduction_basics_part_ii

11

Arrays – Part I

● What is an array? In brief: array are like tables.

– A table or list of values of the same type.

– (Formally: A CTS type, describing a couple of objects of the same static type.)

– Its elements/items can be accessed randomly with O(1) complexity.

– Arrays can neither grow nor shrink in .Net!

● What kinds of arrays exist?

– One dimensional and multi dimensional (rectangular or jagged) arrays.

● => Array creation and initialization.

– Can be created/initialized with length and default values using the []-declarator.

– Can be created/initialized with literals.

– Can be populated with loops (esp. with for loops) using the indexer.

– Can be created/initialized with special APIs.

● The array type of another type needs not (and cannot) be declared as a UDT ahead, instead the arraytype is declared by its usage. - The same is valid forpointer types. Just the declarators [] and * are used.

● Arrays are the only collections w/ direct support inthe CLR.

● There are some static utility-methods in the class Array (CreateInstance(), ConvertAll() etc.).

● Multi dimensional arrays are almost nowhere usedin .Net framework. There are better alternatives andthey are usually not used in applicationprogramming. Sometimes multidimensional arrayscan be useful in very low level code to get moreperformance, but these performance benefits aretypically very small.

Page 12: (3) c sharp introduction_basics_part_ii

12

Arrays – Part II

● Accessing array elements and length.

– The index operator ([], aka "indexer" in C#) is used to access the elements.

– The array indexes are 0-based in general.

– On creation the length of the array is specified with the []-declarator.

– Arrays "know" their (immutable) length (public property Length).

– So the indexes' range is [0, Length[ in general.

– If array access exceeds this range, an IndexOutOfRangeException will be thrown.

● Arrays can only be created on the heap!

● If arrays are passed to member functions, they are not copied!

● Arrays must be created on the heap, becausetheir length is only defined at run time. In C++ it ispossible to define arrays on the stack, but thentheir size is fixed at compile time.

Page 13: (3) c sharp introduction_basics_part_ii

13

Procedural Programming

● C# doesn't have a notation of a global namespace, free functions don't exist.

– C# only allows the definition of types and their member functions.

● Member functions are called methods in C# and in the .Net framework.

● But in C# procedural programming can be implemented with static methods.

● Methods contain code.

– Execute statements.

– Call other methods.

● Writing procedural code.

– I.e. call static methods from within other static methods.

– Start coding in Main() and call other static methods in Main().

● We have discussed some details of imperativeprogramming in C#, now we'll discussprocedural programming.

Page 14: (3) c sharp introduction_basics_part_ii

14

public class A { // The type

}

(int x, int y, string s = "hello")

Optional parameter

Definition of (static) Methods

public static int GetCount

{ // A block of code (method body)

}

return 42;

Type of returned valueMethod name Parameter list

Method body

Return value from method

Type definition

● In some future code examples the "surrounding type definition" will be left away.

– Then only the "bare" method definition will remain then.

● In C# all functions are member functions, or "methods" in .Net's lingo. In following codeexamples the “surrounding type definition” will be left away.

● The return type:● void, if the method does not return a value.

● The method name:● Obey the rules for C# identifiers (PascalCase).● Their identifiers should be meaningful.

● Parameter list:● Can be overloaded (type and count of parameters).● Arguments are getting passed by value in general, so they are copied when being

passed (use out/ref modifiers in the parameter list and the call to change this default).● Don't use call by reference (side effects), better use return values.

● A variable parameter list can be defined as well (all arguments must be of the sametype, but their count is open until being called). The declaration of such a parameter listis performed by using a parameter of type params array <type>[]; a variable parameterlist must be the last (leftmost) parameter in a parameter list.

● Optional parameters can be defined as the very leftmost parameters as well. We haveto assign their default value within the parameter list.

● The return type and the types of the parameters make up the signature of a method.● Multiple methods can have the same name in the same type and only differ in the

parameter list. These methods are then called overloads.● The body of the method.● Return a value from a method by using the return keyword with the value. Methods

declared as void need not to return explicitly. If during execution a return was executed, nostatements following that return will be executed (save such statements in finally blocks).

Page 15: (3) c sharp introduction_basics_part_ii

15

Calling static Methods

● Syntax of calling methods with positional argument passing:

● Syntax of calling methods with named argument passing:

● Even if no parameters are to be passed, a pair of empty parentheses "()" has to be written!

ResultType result = TypeName.Method(arg1, arg2);

ResultType result = TypeName.Method(param1: arg1, param2: arg2); // or:ResultType result = TypeName.Method(param2: arg2, param1: arg1);

Page 16: (3) c sharp introduction_basics_part_ii

16

16

Thank you!