C# - Introduction
Language Fundamentals:
Data Types
string
Objects and Classes
Methods
Iteration and Selection
Arrays
C#
• All program logic must be embedded in (typically) a class.
Like Java.
• Every executable program must contain a Main-method.
The Main-method is the starting point of the application.
• The Main-method has several overloads:
– static int Main(string[] args), static void Main(string[] args),
static void Main() or static int Main()
• C# is case-sensitive
• C# supports operator and method overloading
• No multiple enhiritance (only interfaces – as in Java)
• All classes inherit object – as in Java
• Garbage-collection
C#
- data types
Keyword Description Special format for literals
bool Boolean true false
char 16 bit Unicode character 'A' 'x0041' 'u0041'
sbyte 8 bit signed integer none
byte 8 bit unsigned integer none
short 16 bit signed integer none
ushort 16 bit unsigned integer none
int 32 bit signed integer none
uint 32 bit unsigned integer U suffix
long 64 bit signed integer L or l suffix
ulong 64 bit unsigned integer U/u and L/l suffix
float 32 bit floating point F or f suffix
double 64 bit floating point no suffix
decimal 128 bit high precision M or m suffix
string character sequence "hello", @"C:dirfile.txt"
C#
- the string data type
• string is an alias for System.String – so
string is a class
• Many useful properties and methods are
offered by string:
– Length (property)
– Concat()
– CompareTo()
– Etc.
C#
- using types in C#
• Declaration before use (compiler checked)
• Initialisation before use (compiler checked)
public class App
{
public static void Main()
{
int width, height;
width = 2;
height = 4;
int area = width * height;
int x;
int y = x * 2;
...
}
}
declarations
declaration + initialization
error, x is not initialised
Arithmetics I
• C# offers the usual arithmetic operations: +, -, * , /
and % (modulus)
• +, - and * are defined as usual
• / is overloaded:
– If the operand are integers, the integer division is
applied:
• 23 / 4 gives 5
– If one of the operands is a floating point, the result also
is a floating point:
• 23.0 / 4 gives 5.75
– typecasting may be necessary
Arithmetics II
• The modulus operator yields the remainder with integer
division:
– 23 % 4 gives 3, because 23 divide by 4 yields the quotient 5 and
the remainder 3
• The usual rules of operator precedence are valid in C#:
– 2 + 3 * 4 = 2 + (3 * 4) = 14
– (2+3) * 4 = 20
Arithmetics and Data Types
• In C# the result of an arithmetic operation has the
“larger” type of the two operands:
– int + long yields a long
– float + double yields a double
– byte + float yields a float
– etc.
• It is always possible to assign a variable of a
“larger” type a value of a “smaller” type
– int x = 23;
– long y = x;
Type Casting
• One can change the type of an expression using explicit
casting:
int count = 24;
int total = 100;
float average = (float) total / count ;
• Syntax: (data type) variable name
• Type casting has higher precedence than arithmetic
operations
C#
- type conversion
• Some type conversions are done automatically
– from “smaller” to “larger” type
• Otherwise explicit casting og conversion must be applied:
– Type cast: prefix the type name in parentheses
– Conversion: use the System.Convert-class
int i = 5;
double d = 3.2;
string s = "496";
d = i;
i = (int) d;
i = System.Convert.ToInt32(s);
implicit cast
Explicit cast is needed
Conversion
C#
- Namespaces and Using
• Namespaces is a tool for structuring programs and systems
• Makes it possible to use the same names (identifiers) in
different parts of an application.
• Namespaces may be nested
• Visual Studio creates default a namespace with the same
name as the project
• using <namespace name> tells the compiler where to look
for definitions that our program refers to
• Namespaces are not the same as Java-packages, but they
are used for the same things and there are similarities
C#
- constructors
• Are called when an object is created:
– HelloClass h = new HelloClass("Carl");
– This constructor takes a parameter of type string
• The constructor’s job is to initialise the object, that is to
assign valid values to the instance variables of the object
• A default-constructor is created automatically:
– The default-constructor takes no arguments and initialises the
instance variables to their default values
– The default-constructor may be overridden be writing a
constructor with no parameters
C#
- value- and reference-types
• Objects of value-type are stack allocated – objects
of reference type are allocated on the heap
• Value types dies, when control goes out of the
scope, where they are declared – reference types
removed by the garbage collector
• Value types are copied with assignment – with
reference types a reference (the address) is copied
C#
- reference types - example
• creation, assignment and comparison:
Customer c1, c2, c3;
string s1, s2;
c1 = new Customer("Flemming Sander", 36259);
c2 = new Customer(”Bjarne Riis", 55298);
c3 = null; // c3 refers to nothing
c3 = c1; // c3 refers to the same object as c1
if (c1 == null) ... // is c1 referring to something?
if (c1 == c2) ... // compare references
if (c1.Equals(c2)) ... // compares object-values
C#
- When are objects equal?
• Classes ought to override the Equals-method
public class Customer
{
.
.
.
public override bool Equals(object obj)
{
Customer other;
if ((obj == null) || (!(obj is Customer)))
return false; // surely not equal
other = (Customer) obj; // explicit typecast
return this.id == other.id; // equal if ids are...
}
}
C#
- Boxing and Unboxing
• C# converts automatically between simple value and
object
– value => object = "boxing“ (the value is “wrapped in a box”)
– object => value = "unboxing“ (the value is unwrapped again)
int i, j;
object obj;
string s;
i = 32;
obj = i; // boxing (copy)
i = 19;
j = (int) obj; // unboxing!
s = j.ToString(); // boxing!
s = 99.ToString(); // boxing!
C#
- arrays
• Arrays are reference types
– Created from the Array-class in FCL
– Created using the new-operator
– 0-based indexing
– Are initialised with default value (0 if numeric, null if reference)
int[] a;
a = new int[5];
a[0] = 17;
a[1] = 32;
int x = a[0] + a[1] + a[4];
int l = a.Length;
Access element 1
Creation
Number of elements
C#
- enumerations
• Originally a C/C++ construction used to assigning
symbolic names to numerical values:
enum Month {
January= 1, February = 2,…,December = 12
}
public static void GetSeason(Month m)
{
switch(m)
{
case Month.January:
Console.WriteLine(”Winter”);
……
C#
- structs
• In some ways like a class, but there are
differences:
– Can have instance variables and methods
– Cannot have a default constructor
– Variables of a struct-type are value types and as such
stack allocated
– Can only inherit from interfaces
– Cannot be inherited from
• Can be used to implement ADTs, but no
inheritance and polymorphism
Decision Constructs
• To control the flow of program execution, C# defines two
simple constructs to alter the flow of your program
– The if/else statement
– The switch statement
• Like Java
C#
- selection and iteration
x = obj.foo();
if (x > 0 && x < 10)
count++;
else if (x == -1)
...
else {
...
}
while (x > 0)
{
...
x--;
} for (int k = 0; k < 10; k++)
{
...
}
C#
- foreach-loop
• foreach loop is used to sweep over collections
as arrays
– Reduces the risk of indexing errors
int[] data = { 1, 2, 3, 4, 5 };
int sum = 0;
foreach (int x in data)
{
sum += x;
}
foreach
type value collection
Method Parameter Modifiers
• C# provides a set of parameter modifiers that control how
arguments are sent into (and possibly returned from) a
given method.
The Default Parameter-Passing
// Arguments are passed by value by default.
public static int Add(int x, int y)
{
int ans = x + y;
// Caller will not see these changes
// as you are modifying a copy of the
// original data.
x = 10000;
y = 88888;
return ans;
}
The out Modifier
// Output parameters are allocated by the member.
public static void Add(int x, int y, out int ans)
{
ans = x + y;
}
static void Main(string[] args)
{
// No need to assign local output variables.
int ans;
Add(90, 90, out ans);
Console.WriteLine("90 + 90 = {0} ", ans);
}
The ref Modifier
public static void SwapStrings(ref string s1,
ref string s2)
{
string tempStr = s1;
s1 = s2;
s2 = tempStr;
}
static void Main(string[] args)
{
string s = "First string";
string s2 = "My other string";
Console.WriteLine("Before: {0}, {1} ", s, s2);
SwapStrings(ref s, ref s2);
Console.WriteLine("After: {0}, {1} ", s, s2);
}
The params Modifier
// Return average of 'some number' of doubles.
static double CalculateAverage(params double[] values)
{
double sum = 0;
for (int i = 0; i < values.Length; i++)
sum += values[i];
return (sum / values.Length);
}
static void Main(string[] args)
{
// Pass in a comma-delimited list of doubles...
double average;
average = CalculateAverage(4.0, 3.2, 5.7);
Console.WriteLine("Average of 4.0, 3.2, 5.7 is: {0}",
average);
// ...or pass an array of doubles.
double[] data = { 4.0, 3.2, 5.7 };
average = CalculateAverage(data);
Console.WriteLine("Average of data is: {0}", average);
}
C#
- Methods
• A class may have two kind of methods:
– Instance methods
– Static methods (class methods)
– Instance methods need an object to be invoked
– Static methods are called using the class name
only
C#
- Example
• The array-class in BCL (FCL)
– The class is a member of namespace System (System.Array)
namespace System
{
public class Array
{
public int GetLength(int dimension)
{ ... }
public static void Sort(Array a)
{ ... }
.
.
.
}
}
instance method
static method
C#
- calling the methods
/* main.cs */
using System;
public class App
{
public static void Main()
{
int[] data = { 11, 7, 38, 55, 3 };
Array.Sort(data);
for (int i=0; i<data.GetLength(0); i++)
Console.WriteLine(i + ": " + data[i]);
}
}
Class-method
Instance-method

Introduction to C#

  • 1.
    C# - Introduction LanguageFundamentals: Data Types string Objects and Classes Methods Iteration and Selection Arrays
  • 2.
    C# • All programlogic must be embedded in (typically) a class. Like Java. • Every executable program must contain a Main-method. The Main-method is the starting point of the application. • The Main-method has several overloads: – static int Main(string[] args), static void Main(string[] args), static void Main() or static int Main() • C# is case-sensitive • C# supports operator and method overloading • No multiple enhiritance (only interfaces – as in Java) • All classes inherit object – as in Java • Garbage-collection
  • 3.
    C# - data types KeywordDescription Special format for literals bool Boolean true false char 16 bit Unicode character 'A' 'x0041' 'u0041' sbyte 8 bit signed integer none byte 8 bit unsigned integer none short 16 bit signed integer none ushort 16 bit unsigned integer none int 32 bit signed integer none uint 32 bit unsigned integer U suffix long 64 bit signed integer L or l suffix ulong 64 bit unsigned integer U/u and L/l suffix float 32 bit floating point F or f suffix double 64 bit floating point no suffix decimal 128 bit high precision M or m suffix string character sequence "hello", @"C:dirfile.txt"
  • 4.
    C# - the stringdata type • string is an alias for System.String – so string is a class • Many useful properties and methods are offered by string: – Length (property) – Concat() – CompareTo() – Etc.
  • 5.
    C# - using typesin C# • Declaration before use (compiler checked) • Initialisation before use (compiler checked) public class App { public static void Main() { int width, height; width = 2; height = 4; int area = width * height; int x; int y = x * 2; ... } } declarations declaration + initialization error, x is not initialised
  • 6.
    Arithmetics I • C#offers the usual arithmetic operations: +, -, * , / and % (modulus) • +, - and * are defined as usual • / is overloaded: – If the operand are integers, the integer division is applied: • 23 / 4 gives 5 – If one of the operands is a floating point, the result also is a floating point: • 23.0 / 4 gives 5.75 – typecasting may be necessary
  • 7.
    Arithmetics II • Themodulus operator yields the remainder with integer division: – 23 % 4 gives 3, because 23 divide by 4 yields the quotient 5 and the remainder 3 • The usual rules of operator precedence are valid in C#: – 2 + 3 * 4 = 2 + (3 * 4) = 14 – (2+3) * 4 = 20
  • 8.
    Arithmetics and DataTypes • In C# the result of an arithmetic operation has the “larger” type of the two operands: – int + long yields a long – float + double yields a double – byte + float yields a float – etc. • It is always possible to assign a variable of a “larger” type a value of a “smaller” type – int x = 23; – long y = x;
  • 9.
    Type Casting • Onecan change the type of an expression using explicit casting: int count = 24; int total = 100; float average = (float) total / count ; • Syntax: (data type) variable name • Type casting has higher precedence than arithmetic operations
  • 10.
    C# - type conversion •Some type conversions are done automatically – from “smaller” to “larger” type • Otherwise explicit casting og conversion must be applied: – Type cast: prefix the type name in parentheses – Conversion: use the System.Convert-class int i = 5; double d = 3.2; string s = "496"; d = i; i = (int) d; i = System.Convert.ToInt32(s); implicit cast Explicit cast is needed Conversion
  • 11.
    C# - Namespaces andUsing • Namespaces is a tool for structuring programs and systems • Makes it possible to use the same names (identifiers) in different parts of an application. • Namespaces may be nested • Visual Studio creates default a namespace with the same name as the project • using <namespace name> tells the compiler where to look for definitions that our program refers to • Namespaces are not the same as Java-packages, but they are used for the same things and there are similarities
  • 12.
    C# - constructors • Arecalled when an object is created: – HelloClass h = new HelloClass("Carl"); – This constructor takes a parameter of type string • The constructor’s job is to initialise the object, that is to assign valid values to the instance variables of the object • A default-constructor is created automatically: – The default-constructor takes no arguments and initialises the instance variables to their default values – The default-constructor may be overridden be writing a constructor with no parameters
  • 13.
    C# - value- andreference-types • Objects of value-type are stack allocated – objects of reference type are allocated on the heap • Value types dies, when control goes out of the scope, where they are declared – reference types removed by the garbage collector • Value types are copied with assignment – with reference types a reference (the address) is copied
  • 14.
    C# - reference types- example • creation, assignment and comparison: Customer c1, c2, c3; string s1, s2; c1 = new Customer("Flemming Sander", 36259); c2 = new Customer(”Bjarne Riis", 55298); c3 = null; // c3 refers to nothing c3 = c1; // c3 refers to the same object as c1 if (c1 == null) ... // is c1 referring to something? if (c1 == c2) ... // compare references if (c1.Equals(c2)) ... // compares object-values
  • 15.
    C# - When areobjects equal? • Classes ought to override the Equals-method public class Customer { . . . public override bool Equals(object obj) { Customer other; if ((obj == null) || (!(obj is Customer))) return false; // surely not equal other = (Customer) obj; // explicit typecast return this.id == other.id; // equal if ids are... } }
  • 16.
    C# - Boxing andUnboxing • C# converts automatically between simple value and object – value => object = "boxing“ (the value is “wrapped in a box”) – object => value = "unboxing“ (the value is unwrapped again) int i, j; object obj; string s; i = 32; obj = i; // boxing (copy) i = 19; j = (int) obj; // unboxing! s = j.ToString(); // boxing! s = 99.ToString(); // boxing!
  • 17.
    C# - arrays • Arraysare reference types – Created from the Array-class in FCL – Created using the new-operator – 0-based indexing – Are initialised with default value (0 if numeric, null if reference) int[] a; a = new int[5]; a[0] = 17; a[1] = 32; int x = a[0] + a[1] + a[4]; int l = a.Length; Access element 1 Creation Number of elements
  • 18.
    C# - enumerations • Originallya C/C++ construction used to assigning symbolic names to numerical values: enum Month { January= 1, February = 2,…,December = 12 } public static void GetSeason(Month m) { switch(m) { case Month.January: Console.WriteLine(”Winter”); ……
  • 19.
    C# - structs • Insome ways like a class, but there are differences: – Can have instance variables and methods – Cannot have a default constructor – Variables of a struct-type are value types and as such stack allocated – Can only inherit from interfaces – Cannot be inherited from • Can be used to implement ADTs, but no inheritance and polymorphism
  • 20.
    Decision Constructs • Tocontrol the flow of program execution, C# defines two simple constructs to alter the flow of your program – The if/else statement – The switch statement • Like Java
  • 21.
    C# - selection anditeration x = obj.foo(); if (x > 0 && x < 10) count++; else if (x == -1) ... else { ... } while (x > 0) { ... x--; } for (int k = 0; k < 10; k++) { ... }
  • 22.
    C# - foreach-loop • foreachloop is used to sweep over collections as arrays – Reduces the risk of indexing errors int[] data = { 1, 2, 3, 4, 5 }; int sum = 0; foreach (int x in data) { sum += x; } foreach type value collection
  • 23.
    Method Parameter Modifiers •C# provides a set of parameter modifiers that control how arguments are sent into (and possibly returned from) a given method.
  • 24.
    The Default Parameter-Passing //Arguments are passed by value by default. public static int Add(int x, int y) { int ans = x + y; // Caller will not see these changes // as you are modifying a copy of the // original data. x = 10000; y = 88888; return ans; }
  • 25.
    The out Modifier //Output parameters are allocated by the member. public static void Add(int x, int y, out int ans) { ans = x + y; } static void Main(string[] args) { // No need to assign local output variables. int ans; Add(90, 90, out ans); Console.WriteLine("90 + 90 = {0} ", ans); }
  • 26.
    The ref Modifier publicstatic void SwapStrings(ref string s1, ref string s2) { string tempStr = s1; s1 = s2; s2 = tempStr; } static void Main(string[] args) { string s = "First string"; string s2 = "My other string"; Console.WriteLine("Before: {0}, {1} ", s, s2); SwapStrings(ref s, ref s2); Console.WriteLine("After: {0}, {1} ", s, s2); }
  • 27.
    The params Modifier //Return average of 'some number' of doubles. static double CalculateAverage(params double[] values) { double sum = 0; for (int i = 0; i < values.Length; i++) sum += values[i]; return (sum / values.Length); } static void Main(string[] args) { // Pass in a comma-delimited list of doubles... double average; average = CalculateAverage(4.0, 3.2, 5.7); Console.WriteLine("Average of 4.0, 3.2, 5.7 is: {0}", average); // ...or pass an array of doubles. double[] data = { 4.0, 3.2, 5.7 }; average = CalculateAverage(data); Console.WriteLine("Average of data is: {0}", average); }
  • 28.
    C# - Methods • Aclass may have two kind of methods: – Instance methods – Static methods (class methods) – Instance methods need an object to be invoked – Static methods are called using the class name only
  • 29.
    C# - Example • Thearray-class in BCL (FCL) – The class is a member of namespace System (System.Array) namespace System { public class Array { public int GetLength(int dimension) { ... } public static void Sort(Array a) { ... } . . . } } instance method static method
  • 30.
    C# - calling themethods /* main.cs */ using System; public class App { public static void Main() { int[] data = { 11, 7, 38, 55, 3 }; Array.Sort(data); for (int i=0; i<data.GetLength(0); i++) Console.WriteLine(i + ": " + data[i]); } } Class-method Instance-method