C# BASICS


Content


App Structure
Types
Statements, Expressions, Operators
Arrays
Example: Bubble sort
Example: Sieve of Eratosthenes




App Structure

Minimal App


using System;

namespace BasicApp
{
    class App
    {
        static void Main()
        {
            Console.WriteLine("Hi!");
        }
    }
}
  • Type definition holds app logic
  • Application Object: Class that holds the Main method

Main Method

static void Main() 
{
   // code ...
}
static int Main() 
{
   // code ...
   return 0;         // returns integer
}
static int Main(string[] args) 
{
    var t = args[0];  // process command-line arguments

    // code ...
    return 42;
}

Main Method #2


  • Entry point of .exe program
  • Declared inside class or struct
  • Must be static
  • Should not be public (default: private)
  • Enclosing class/struct not required to be static
  • Either void or int return type
  • With or without string[] parameter

Typical C# Project


  • Consists of 1+ files
  • Each file has 0+ namespaces
  • Namespace contains other namespaces or holds types
    • classes
    • structs
    • interfaces
    • enumerations
    • delegates




Types

Types

  • C# strongly-typed language
  • Variables have a type
  • Expressions that eval to values have a type
  • Method signature specifies types
    • input params are typed
    • return value is typed
  • .NET class library defines
    • built-in numeric types
    • complex types
      • file system
      • network connections
      • collections

Types #2


Type provides information for the compiler

  • Max/Min values
  • Members (methods, fields, events, ...)
  • Base type
  • Location where memory will be allocated at runtime
    • Stack vs. heap
  • Operations that are supported

Types #3


Compiler checks
int x = 5;
int y = x - 2;      // compiler allows subtraction

bool foo = true;
int z = x + foo;    // allowed?

Explicit/Implicit types
// Explicit type 
int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Implicit type
var limit = 100;   // compiler infers integer

Types #4


  • After variable declaration
    • no redelaration with new type
    • cannot assign incompatible value
  • Values can be converted to other types
    • Compiler performs type conversion when no data loss
    • Conversion with data loss requires cast!

int x = 0;
float x = 3.0f;      // redeclaration

int y = 2.3f;        // incompatible type, requires cast
int z = (int) 4.4f;  // ok, with explicit cast!

float w = 1;         // auto type conversion 

Built-in/Custom Types


  • Set of built-in numeric types (in .NET)
    • integers
    • floating point values
    • boolean values
    • text chars
    • decimal values
  • Custom types
    • Use struct, class, interface or enum

Common Type System (CTS)


Two important aspects of .NET types

  1. Supports inhertiance
    • Derive from a base class
    • Derived class inherits members (with restricitons)
    • Build up an inhertiance hierarchy
    • All types ultimately derive from System.Object
      • C# keyword: object
  2. Each type in CTS is either value or reference type
    • Struct types - value types
    • Class types - reference types

Value/Reference Types

Have different compile-time rules and run-time behaviour
  • Value Types
    • variables directly hold their values
    • No heap allocation (no overhead, fast)
    • Struct, Enum
    • Value types are sealed (cannot be base class)
  • Reference Types
    • Defined as class, interface, delegate or array
    • Allocated on managed heap
    • Variable holds a reference to the location of the object
    • Cleaned up by garbage collection
    • Support inheritance

Boxing/Unboxing

  • Boxing converts a value type to the object type
  • Wrapped in System.Object and allocated on heap
  • Boxing is implicit
  •     
    int x = 3;
    object o = x;    // box x into o, move from stack to heap
    
    
  • Unboxing extracts value from the object
  • Unboxing is explicit
  •     
    object o = 123;
    int x = (int) o;  // Explicit unboxing
    
  • Notable for performance!




Statements

Statements

  • Everything that is performed by a program
    • variable declarations
    • value assignments
    • method calls
    • looping through collections
    • branching, etc...
  • Control flow: order of the statements that are executed
  • Statement is 
    • either single line statement that ends on semicolon
    • or series of single line statements in a block enclosed in   { ... }
    • blocks may be nested

Declaration Statements


Introduces new variable or constant

// Variable declaration
double d;

// Declaration with assignment
double f = 2;

// Constant declaration statement
const double pi = 3.14159;

Expression Statements


Statements that calc a value have to store the value in a variable

// Expression statement stores value in a
a = 3.14 * (radius * radius);

// what happens here?
b * 3;

// Method invocation
System.Console.WriteLine("Hi!");

// Expression statement create new object
List<string> names = new List<string>();

Selection Statements

Branch to different blocks of code depending on a condition
bool cond = false;
if(cond){ 
  ... 
} else {
 ....
}

// Else statement is optional
if(cond) { ... } 

// If statements are nestable
if(cond1) {
 if(cond2) {
   ...
 } else { ... }
} else { if(cond3) { ... } }

Selection Statements #2


int curCase = 4;

switch(curCase) {
  case 1:
    System.Console.WriteLine("Case 1!");
    break;
  case 2:
    System.Console.WriteLine("Case 2!");
    break;
  case 42:
    System.Console.WriteLine("Case 42!");
    break;
  default: 
    System.Console.WriteLine("Any other case...");
    break;
}

Iteration Statements

Repeatedly perform something
// For loop
for(var i = 0; i < 10; i++) { ... }

// Foreach loop
int[] digits = { 1, 2, 3, 4, 5, 6 }
foreach(var i in digits) { ... }

// While loop
int i = 0; 
while(i < 6) { ... ; i++; }

// Do-while loop
i = 0;
do { ...; i++; }
while(i < 6);

Jump Statements

Jump control flow to other block of code

  • Return Statement
    • Terminates current method and returns to calling method
    • Optional return value
    • If return value is void type, return statement not needed
  • Break Statement
    • Terminates closest enclosing loop or switch statement
    • Pass control flow to next statement
  • Continue Statement
    • Pass control to the next iteration of the current loop statement

Expressions


  • Sequence of 1+ operands and 0+ operators that eval to a single value, object, method or namespace
  • Consist of literal value, method invocation, operator and operand or simple name
  • Simple name could be variable name, type member, method parameter, namespace or type
  • (x > 0) && (x < 25) // evaluates to what?
    
    // Expression as method param
    System.Convert.ToInt32("35");
    

Operators

  • Operator is applied to 1+ operands in expression or statement
  • int y = 0;
    // unary operator (++)
    y++;
    
    // unary operator (new)
    var t = new A();
    
    // binary operator (+,-,*,/)
    int z = 2 + y;
    
    // conditional operator (:?) takes three operands
    var b = z > 0 ? true : false;




Arrays

Arrays

Store multiple variables of same type
// Array declaration of size 4 
int[] array1 = new int[4];
// Set array elements
int[] array2 = new int[] { 1, 5, 7, 9 };

// Alternative syntax
int[] array3 = { 1, 5, 7, 9 };

// 2 dim array
int[,] array4 = new int[3,3];
// 2 dim array with init
int[,] array5 = new int[] { { 2, 4, 5}, { 1, 3, 6} };

// Jagged  array
int[][] array6  = new int[6][];
array6[0] = new int[4] { 1, 2, 3, 4 };

Arrays #2

  • Single, Multidimensional or Jagged
  • Dimensions cannot be changed during lifetime
  • Default numeric array elements are zero
  • Default reference elements are null
  • Jagged array is an array of arrays (reference type)
  • Arrays are zero indexed
    • Array with n elements
    • Array elements from 0 to n-1
  • Array elements can be of any type
MyType[] array1 = MyType[4]; 




Code Example

(Bubble Sort)




Code Example

(Sieve of Eratosthenes)



References








Thank you for your attention!

C# Basics

By dinony

C# Basics

  • 434