(3) c sharp introduction_basics_part_ii

Embed Size (px)

DESCRIPTION

This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/3-c-sharp-introductionbasicspartii-38639257 - C# Syntax Cornerstones

Citation preview

  • 1. (3) Introduction of C# Basics Part IINico Ludwig (@ersatzteilchen)

2. 2TOC (3) Introduction of C# Basics Part II C# Syntax Cornerstones 3. 3Control 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.}} 4. 4Control 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. 5. 5Control 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/). Important for .Net 3.5/C#3 and greater (Language INtegrated Query (LINQ)). 6. 6Control 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).int array[] = {1, 2, 3, 4, 5};for (int i = 0; 5 > i; ++i) {Console.WriteLine(array[i]);} Loops are executed sequentially, not in parallel (e.g. on multiple CPU cores). 7. 7Control Structures Iteration foreach Loop Iteration of "IEnumerable/" Collections. The .Net Collection types and intrinsic arrays are IEnumerable/ types. I.e. these types implement the interface IEnumerable/. 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/ types.int array[] = {1, 2, 3, 4, 5};foreach (int item in array) {Console.WriteLine(item);} (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/ and the keywords yield/foreach work together. 8. 8Control 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.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); Loops are executed sequentially, not in parallel (e.g. on multiple CPU cores). 9. 9Control 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. 10. 10Control 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. 11. 11Arrays 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. 12. 12Arrays 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! 13. 13Procedural 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(). 14. 14public class A { // The type}Optional parameterDefinition of (static) Methods(int x, int y, string s = "hello")Type of returned valuepublic static int GetCount{ // A block of code (method body)}return 42;Method name Parameter listMethod bodyReturn value from methodType definition In some future code examples the "surrounding type definition" will be left away. Then only the "bare" method definition will remain then. 15. 15Calling static Methods Syntax of calling methods with positional argument passing:ResultType result = TypeName.Method(arg1, arg2); Syntax of calling methods with named argument passing:ResultType result = TypeName.Method(param1: arg1, param2: arg2);// or:ResultType result = TypeName.Method(param2: arg2, param1: arg1); Even if no parameters are to be passed, a pair of empty parentheses "()" has to be written! 16. 16Thank you!