C# – Variables and Parameters

Variables and Parameters

A variable is a storage location that has modifiable value
A variable can be local, parameter (value, ref, out), field (instance or static) or array element

Stack and Heap
It is a place where variables and constants reside

  1. Stack
    Block of memory for storing local variable and parameters. Logically grows and shrinks as the function enters and exits.
  2. Heap
    Is the memory where objects are stored. Whenever a new object is created, it is allocated on the heap, and a reference to that object is returned. It also stores static fields and during run time the garbage collector deallocates objects to free memory

Definite Assignment
It is impossible to access uninitialized memory

Rules for Assignment

  1. Local variables must be assigned a value before they can be read.
  2. Function arguments must be supplied when a method is called (unless marked
    as optional
  3. All other variables (such as fields and array elements) are automatically initialized
    by the runtime.

Default Values
All type instance have default value

Type Default Value
All reference types null
All numeric and enum types 0
char type ‘\0’
bool type false

Use default keyword to get the default value, mostly useful with generics

decimal d = default (decimal);

Parameters

Sequence of arguments which needs to be provided for that method

you can control how parameters are passed with ref and out modifiers

Parameter modifier Passed by Assignment
NONE Value going in
ref Reference going in
out Reference going out

Passing arguments by value

  • For default arguments are passed by value (create a copy)
  • For reference only reference is copied not object

The ref modifier

  • Pass by reference
  • Essential in implementing a swap method
class Test
{
static void Foo (ref int p)
{
p = p + 1; // Increment p by 1
Console.WriteLine (p); // Write p to screen
}
static void Main()
{
int x = 8;
Foo (ref x); // Ask Foo to deal directly with x
Console.WriteLine (x); // x is now 9
}
}

The out modifier

  1. Need not be assigned before going into the function
  2. Must be assigned before it comes out of the function
  3. Used to get multiple return values back from a method
class Test
{
static void Split (string name, out string firstNames,out string lastName)
{
      int i = name.LastIndexOf (' ');
      firstNames = name.Substrings (0, i);
      lastName = name.Substrings (i + 1);
}

static void Main()
{
     string a, b;
     Split ("Stevie Ray Vaughan", out a, out b);
     Console.WriteLine (a); // Stevie Ray
     Console.WriteLine (b); // Vaughan
}

}

The params modifier

  • Method can accept any number of arguments of a particular type
  • Parameter type must be declared as an array
class Test
{
static int Sum (params int[] ints)
{
int sum = 0;
for (int i = 0; i < ints.Length; i++)
sum += ints[i]; // Increase sum by ints[i]
return sum;
}
static void Main()
{
int total = Sum (1, 2, 3, 4);
Console.WriteLine (total); // 10
}
}

or

int total = Sum (new int[] { 1, 2, 3, 4 } ); 

Optional parameters
A parameter is optional if it specifies a default value in its declaration

void Foo (int x = 23) { Console.WriteLine (x); }

Optional parameters may be omitted when calling the method:
Foo(); // 23


Mandatory parameters must occur before optional parameters in both the method
declaration and the method call (the exception is with params arguments, which still
always come last).

Named arguments

Instead of identifying argument by position , argument can be identified by name and in any order.

void Foo (int x, int y) { Console.WriteLine (x + ", " + y); }
void Test()
{
Foo (x:1, y:2); // 1, 2
}

You can mix named and positional arguments:
Foo (1, y:2);

Named arguments are particularly useful in conjunction with optional parameters.

void Bar (int a = 0, int b = 0, int c = 0, int d = 0) { ... }
Bar (d:3);

var—Implicitly Typed Local Variables

var can be used if he compiler is able to infer the type implicitly typed variables are statically typed

C# – Arrays

Arrays

Overview

  • Inherit from System.Array class
  • Is a reference type object
    int[] a = null;
  • Is has fixed number of variables
  • Arrays are stored in continous block of memory
  • Arrays are denoted with square brackets after the element type
    char[] vowels = new char[5];
  • Square brackets are used to access the index of the array

Enumeration

  • For loop
    for (int i = 0; i < vowels.Length; i++)
    Console.Write (vowels[i]); // aeiou
    
  • Foreach loop
    int[] myArray = {1,2,3};
    foreach (int val in myArray)
         Console.WriteLine(val);
    

    Using static Array

    Array.ForEach (new[] {1, 2, 3 }, Console.WriteLine); 

Property

Length Number of elements in the array
LongLength Total number of elements in the array
Rank Returns number of dimensions in array

Methods

GetLength() Length for a given dimension
GetLongLength Length for a given dimension
GetLowerBound Useful with nonzero indexed arrays
GetUpperBound Returns same result as adding GetLowerBound to GetLength
Clone() Duplicate Array

arrayB = arrayA.Clone();

Array Initialization

char[] vowels = new char[] {'a','e','i','o','u'};
char[] vowels = {'a','e','i','o','u'};

Default Element Initialization

The default value for a type is the result of a bitwise zeroing of memory.

Value types versus reference types in Array
When the element type is a value type, each element value is allocated as part of the array.
For example:

public struct Point { public int X, Y; }
...
Point[] a = new Point[1000];
int x = a[500].X; // 0

Creating array for class object will allocate null, therefore you cannot access the value directly instead you will need to use iteration using for each loop to access the object value.

public class Point { public int X, Y; }
...
Point[] a = new Point[1000];
int x = a[500].X; // Runtime error, NullReferenceException

Multidimensional Arrays

  1. Rectangular - n-dimensional block of memory
    Declared using commas to separate each dimension

    int[,] matrix = new int[3,3];

    Iteration

    for (int i = 0; i < matrix.GetLength(0); i++)
    for (int j = 0; j < matrix.GetLength(1); j++)
    matrix[i,j] = i * 3 + j;
    

    Initialization

    int[,] matrix = new int[,]
    {
    {0,1,2},
    {3,4,5},
    {6,7,8}
    };
    
  2. Jagged - arrays of arrays
    Declared using successive square brackets to represent each dimension

    int[][] matrix = new int[3][];

    Each inner array can be an arbitrary length
    Each inner array is implicitly initialized to null rather than an empty array

    for (int i = 0; i < matrix.Length; i++)
    {
    matrix[i] = new int[3]; // Create inner array
    for (int j = 0; j < matrix[i].Length; j++)
    matrix[i][j] = i * 3 + j;
    }
    

    Initialization

    int[][] matrix = new int[][]
    {
    new int[] {0,1,2},
    new int[] {3,4,5},
    new int[] {6,7,8,9}
    };
    

Simplified Array Initialization Expressions

  1. Omit new operator
    char[] vowels = {'a','e','i','o','u'};
    int[,] rectangularMatrix =
    {
    {0,1,2},
    {3,4,5},
    {6,7,8}
    };
    
    int[][] jaggedMatrix =
    {
    new int[] {0,1,2},
    new int[] {3,4,5},
    new int[] {6,7,8}
    };
    
  2. Use var keyword
    var i = 3; // i is implicitly of type int
    var s = "sausage"; // s is implicitly of type string
    // Therefore:
    var rectMatrix = new int[,] // rectMatrix is implicitly of type int[,]
    {
    {0,1,2},
    {3,4,5},
    {6,7,8}
    };
    var jaggedMat = new int[][] // jaggedMat is implicitly of type int[][]
    {
    new int[] {0,1,2},
    new int[] {3,4,5},
    new int[] {6,7,8}
    };
    

You can also let the compiler infer the array type

var vowels = new[] {'a','e','i','o','u'}; // Compiler infers char[]

Bounds Checking
All array indexing is bounds-checked by the run-time
IndexOutOfRangeException thrown if invalid index

Searching
BinarySearch methods

For rapidly searching a sorted array for a particular item

IndexOf / LastIndex methods

For searching unsorted arrays for a particular item

Find / FindLast / FindIndex / FindLastIndex / FindAll / Exists / TrueForAll

For searching unsorted arrays for item(s) that satisfy a given Predicate

C# – String Type

String Type

Overview

  • System.String
  • Immutable sequence of Unicode characters
  • Specified in double quotes
  • Is reference type
  • Escape sequence valid for char literals work inside strings
    eg string a = "Here's a tab:\t";
  • Whenever backslash is needed you need to write twice
    string a1 = "\\\\server\\fileshare\\helloworld.cs";

Verbatim String Literals

  • C# allows verbatim string literals, prefixed with @ and does not support escape sequence
    eg: string a2 = @ "\\server\fileshare\helloworld.cs";
  • Include double-quote character in a verbatim literal by writing twice
    string xml = @"";

String concatenation

  • + operator concatenates two strings
    string s = "a" + "b";
  • If one of the value is non string, ToString() method is called on the value
    string s = "a" + 5; // a5

Better solution to use:
System.Text.StringBuilder

String interpolation (C# 6)

String preceded with the $ character is called an interpolated string

Interpolated strings can include expressions inside braces

int x = 4;
Console.Write ($"A square has {x} sides"); // Prints: A square has 4 sides

To change the format

string s = $"255 in hex is {byte.MaxValue:X2}"; // X2 = 2-digit Hexadecimal
// Evaluates to "255 in hex is FF"

int x = 2;
string s = $@"this spans {
x} lines";

String comparisons

Use CompareTo() method