C#
Tutorial for C++ Students in CS1120
Introduction to C#

Features of C#
Very similar to Java
70% Java, 10% C++, 5% Visual Basic, 15% new
Structure of C# Programs

•If no namespace is specified =>
anonymous default namespace
•Namespaces may also contain structs,
interfaces, delegates and enums
•Namespace may be "reopened"
in other files
•Simplest case: single class, single
file, default namespace
My First C# program
Summation of two integers as Console
Application
•uses
the namespace System
•entry point must be called
•output goes to the console
•file name and class name need not to
be identical.
Summation of two integers as Console
Application


A Program Consisting of 2 Files
Prog.cs using System; class Prog { static
void { Counter
c = new Counter(); c.Add(3);
c.Add(5); Console.WriteLine("val
= " + c.Val()); } }

Types
Unified Type System

All types are compatible with object
can be assigned
to variables of type object
all operations
of type object are applicable to them
Value Types versus Reference Types
|
|
Value Types |
Reference Types |
|
variable contains |
value |
reference |
|
stored |
On
stack |
heap |
|
initialization |
0,
false, '\0' |
null |
|
assignment |
copies
the value |
copies
the reference |
|
example |
int i = 17; |
string s = "Hello"; |
|
|
int j= i; |
string s1= s; |
|
|
|
|
Simple Types
|
|
Long Form |
Range |
|
Sbyte |
System.SByte |
-128 .. 127 |
|
byte |
System.Byte |
0 .. 255 |
|
short |
System.Int16 |
-32768 .. 32767 |
|
ushort |
System.UInt16 |
0 .. 65535 |
|
int |
System.Int32 |
-2147483648 .. 2147483647 |
|
uint |
System.UInt32 |
0 .. 4294967295 |
|
long |
System.Int64 |
-263.. 263-1 |
|
ulong |
System.UInt64 |
0 .. 264-1 |
|
float |
System.Single |
±1.5E-45 .. ±3.4E38 (32 Bit) |
|
double |
System.Double |
±5E-324 .. ±1.7E308 (64 Bit) |
|
decimal |
System.Decimal |
±1E-28 .. ±7.9E28 (128 Bit) |
|
bool |
System.Boolean |
true, false |
|
char |
System.Char |
Unicode character |
Compatibility between Simple Types

Enumerations
List of named constants
Declaration (directly in a namespace)
enum Color {red, blue, green} // values: 0, 1, 2
enum
Access {personal=1, group=2, all=4}
enum Access1 : byte {personal=1,
group=2, all=4}
Use
Color c =
Color.blue; // enumeration constants must be qualified
Access a =
Access.personal | Access.group;
if
((Access.personal & a) != 0) Console.WriteLine("access granted");
Operations on Enumerations
|
Compare |
if (c == Color.red) ... |
|
if (c > Color.red
&& c <= Color.green) ... |
|
|
|
|
|
+, - |
c = c + 2; |
|
|
|
|
++, -- |
c++; |
|
|
|
|
& |
if ((c & Color.red) ==
0) ... |
|
|
|
|
| |
c = c | Color.blue; |
|
|
|
|
~ |
c = ~ Color.red; |
The compiler does not check if the
result is a valid enumeration value.
Note
§ Enumerations cannot be assigned to int (except after a type cast).
§ Enumeration types inherit from object (Equals,
ToString, ...).
§ Class System.Enum provides operations on enumerations (GetName,
Format, GetValues,
...).
Arrays
One-dimensional Arrays
int[] a = new int[3];
int[] b = new int[]
{3, 4, 5};
int[] c = {3, 4, 5};
SomeClass[]
d = new SomeClass[10]; // Array of references
SomeStruct[] e = new SomeStruct[10]; // Array of values (directly in the array)
int len =
a.Length; // number of elements in a
Multidimensional Arrays
Jagged (like in Java)

![Text Box: int[][] a = new int[2][];
a[0] = new int[3];
a[1] = new int[4];
int x = a[0][1];
int len = a.Length; // 2
len = a[0].Length; // 3](Lect.1b--_C-sharp%20Refresher__a1alalaw_files/image018.gif)
Rectangular (more compact, more efficient access)

![Text Box: int[,] a = new int[2, 3];
int x = a[0, 1];
int len = a.Length; // 6
len = a.GetLength(0); // 2
len = a.GetLength(1); // 3](Lect.1b--_C-sharp%20Refresher__a1alalaw_files/image020.gif)
Class System.String
Can be used as standard type string
string s = "Alfonso";
Note
•Strings are immutable (use
StringBuilder if you want to modify strings)
•Can be concatenated with +: "Don
" + s
•Can be indexed: s[i]
•String length: s.Length
•Strings are reference types =>
reference semantics in assignments
•but their values can be compared with == and != : if (s ==
"Alfonso") ...
•Class String defines many useful
operations:
CompareTo,
IndexOf, StartsWith, Substring, ...
Structs
Declaration
Struct Point {
public int x,
y; // fields
public Point (int x, int y) // constructor
{
this.x = x;
this.y = y;
}
public void MoveTo (int a, int b) // methods
{
x
= a;
y
= b;
}
}
Use
Point p = new
Point(3, 4); // constructor initializes object
on the stack
p.MoveTo(10, 20); // method call
Classes
Declaration
class Rectangle {
Point
origin;
public int width, height;
public Rectangle() {
origin
= new Point(0,0);
width
= height = 0;
}
public Rectangle (Point p, int w, int h) {
origin
= p;
width
= w;
height
= h;
}
public void MoveTo (Point p) {
origin
= p;
}
}
Use
Rectangle r = new
Rectangle(new Point(10, 20), 5, 5);
int area = r.width * r.height;
r.MoveTo(new Point(3, 3));
Expressions
Operators and their Priority
Primary (x) x.y
f(x) a[x] x++ x-- new
typeof sizeof
checked
unchecked
Unary
+ - ~ ! ++x --x (T)x
Multiplicative * /
%
Additive + -
Shift
<< >>
Relational < >
<= >= is as
Equality == !=
Logical AND &
Logical XOR ^
Logical OR |
Conditional AND &&
Conditional OR ||
Conditional c?x:y
Assignment = +=
-= *= /= %=
<<= >>= &= ^= |=
Operators
on the same level are evaluated from left to right
Declarations
Declaration Space
The program area to which a declaration
belongs
Entities can be declared in a ...
-namespace:
Declaration
of classes, interfaces, structs, enums, delegates
-class, interface,
struct: Declaration of fields, methods, properties, events, indexers, ...
-enum:
Declaration
of enumeration constants
-block:
Declaration
of local variables
Scoping rules
-A name must not be declared twice in the
same declaration space.
-Declarations may occur in arbitrary order.
Exception: local variables must be declared
before they are used
Visibility rules
-A name is only visible within its
declaration space
(local variables are only visible after their
point of declaration).
-The visibility can be restricted by
modifiers (private, protected, ...)
Statements
Simple Statements
Empty statement
; // ; is a terminator, not a
separator
Assignment
x = 3 * y + 1;
Method call
string s = "a,b,c";
string[] parts = s.Split(','); // invocation of an object method
(non-static)
s
= String.Join(" + ", parts); // invocation of a class method
(static)
if Statement
if ('0'
<= ch && ch <= '9')
val
= ch -'0';
else if ('A' <= ch && ch <= 'Z')
val
= 10 + ch -'A';
else {
val
= 0;
Console.WriteLine
("invalid character {0}", ch);
}
switch Statement
switch (country) {
case "
language
= "German";
break;
case "
language
= "English";
break;
case null:
Console.WriteLine("no
country specified");
break;
default :
Console.WriteLine("don't
know language of {0}", country);
break;
}
Type of switch expression
numeric, char, enum or string (null ok as a case label).
No fall-through!
Every statement sequence in a case must be terminated
with break (or return, goto, throw).
If
no case label matches à default
If
no default specified à continuation after the switch statement
Loops

foreach Statement

Jumps
break;
For exiting a loop or a switch statement.
There
is no break with a label like in Java (use gotoinstead).
continue; Continues with the next loop iteration.
goto case 3: Can be used in a switch statement to jump to a case
label.
myLab:
...
goto
myLab; //Jumps to the label myLab.
Restrictions:
-no jumps into a block
-no jumps out of a finally block of a try
statement
return Statement

Classes and Structs
Contents of Classes or Structs
class C {
...
fields, constants... // for object-oriented programming
...
methods...
...
constructors,
destructors...
...
properties...// for component-based programming
...
events...
...
indexers...// for amenity
...
overloaded
operators...
...
nested types
(classes, interfaces, structs, enums, delegates)...
}
Classes

Structs

Visibility Modifiers (excerpt)
Public visible where the declaring namespace is known
-Members
of interfaces and enumerations are public by default.
-Types
in a namespace (classes, structs, interfaces, enums, delegates)
have
default visibility internal(visible in the declaring assembly)
private only visible in declaring class or struct
-Members
of classes and structs are private by default
(fields,
methods, properties, ..., nested types)
Example
![Text Box: public class Stack {
private int[] val; // private is also default
private int top; // private is also default
public Stack() {...}
public void Push(int x) {...}
public int Pop() {...}
}](Lect.1b--_C-sharp%20Refresher__a1alalaw_files/image021.gif)
Fields and Constants

Static Fields and Constants

Methods

Static Methods

-"call by value" -formal parameter is a copy of the actual parameter -actual parameter is an expression
Parameters
Value Parameters (input values)
void
Inc(int x) {x = x + 1;}
void
f() {
int
val = 3;
Inc(val);
// val == 3
}
-"call by reference" -formal parameter is an alias for the actual parameter (address of actual parameter is passed) -actual parameter must be a variable
ref Parameters (transition values)
void
Inc(refint x)
{ x = x + 1; }
void
f() {
int
val = 3;
Inc(refval); // val == 4
}
-similar to ref parameters but no value is passed by the caller. -must not be used in the method before it got a value.
out Parameters (output values)
void
Read (outint first, outint
next) {
first
= Console.Read(); next = Console.Read();
}
void
f() {
int
first, next;
Read(outfirst, outnext);
}
Constructors for Classes

Default Constructor

Constructors for Structs

Static Constructors

Destructors

Properties


Conversion Operators
