C# Notes
C# Notes
C# Notes
Introduction to C#
Kurt Nørmark ©
Department of Computer Science, Aalborg University,
Denmark
C# seen in a historic
perspective
Slide Annotated slide Contents Index
References Textbook
• Computer Language
History
The Common
Language
Infrastructure
Slide Annotated slide Contents Index
References Textbook
C# Compilation and
Execution
Slide Annotated slide Contents Index
References Textbook
Differences compared to C.
Program: Demonstrations using System;
of the simple type bool in
C#. Shows boolean class BoolDemo{
constants and how to deal
with the default boolean public static void Main(){
value (false). bool b1, b2;
b1 = true; b2 = default(bool);
Console.WriteLine("The value of b2 is {0}",
b2); // False
}
}
Program: Demonstrations using System;
of the simple type char in
C#. Illustrates character class CharDemo{
constants, hexadecimal
escape notation, and public static void Main(){
character methods. char ch1 = 'A',
ch2 = '\u0041',
ch3 = '\u00c6', ch4 = '\u00d8', ch5 =
'\u00c5',
ch6;
ch6 = char.Parse("B");
Console.WriteLine("{0} {1}",
char.GetNumericValue('3'),
char.GetNumericVal
ue('a'));
}
}
Program: Demonstrations using System;
of numeric types in C#. using System.Globalization;
Illustrates all numeric types
in C#. Exercises minimum class NumberDemo{
and maximum values of the
numeric types. public static void Main(){
sbyte sb1 = sbyte.MinValue; //
Signed 8 bit integer
System.SByte sb2 = System.SByte.MaxValue;
Console.WriteLine("sbyte: {0} : {1}", sb1,
sb2);
byte b1 = byte.MinValue; //
Unsigned 8 bit integer
System.Byte b2 = System.Byte.MaxValue;
Console.WriteLine("byte: {0} : {1}", b1, b2);
short s1 = short.MinValue; //
Signed 16 bit integer
System.Int16 s2 = System.Int16.MaxValue;
Console.WriteLine("short: {0} : {1}", s1, s2);
int i1 = int.MinValue; //
Signed 32 bit integer
System.Int32 i2 = System.Int32.MaxValue;
Console.WriteLine("int: {0} : {1}", i1, i2);
long l1 = long.MinValue; //
Signed 64 bit integer
System.Int64 l2 = System.Int64.MaxValue;
Console.WriteLine("long: {0} : {1}", l1, l2);
float f1 = float.MinValue; // 32
bit floating-point
System.Single f2= System.Single.MaxValue;
Console.WriteLine("float: {0} : {1}", f1, f2);
double d1 = double.MinValue; // 64
bit floating-point
System.Double d2= System.Double.MaxValue;
Console.WriteLine("double: {0} : {1}", d1, d2);
string s = sb1.ToString(),
t = 123.ToString();
}
Program: Output from the sbyte: -128 : 127
numeric demo program. byte: 0 : 255
Output from the program short: -32768 : 32767
above. Reveals minimum ushort: 0 : 65535
and maximum values of int: -2147483648 : 2147483647
all the numeric types. uint: 0 : 4294967295
long: -9223372036854775808 : 9223372036854775807
ulong: 0 : 18446744073709551615
float: -3,402823E+38 : 3,402823E+38
double: -1,79769313486232E+308 :
1,79769313486232E+308
decimal: -79228162514264337593543950335 :
79228162514264337593543950335
Exercise 2.3. Exploring the The type System.Char (a struct) contains a number of useful
type Char methods, and a couple of constants.
You may ask where you find the C# documentation. There are
several possibilities. You can find it at the Microsoft MSDN
web site at msdn.microsoft.com. It is also integrated in Visual
Studio and - to some degree - in Visual C# express. It comes
with the C# SDK, as a separate browser. It is also part of the
documentation web pages that comes with Mono. If you are a
Windows user I will recommend the Windows SDK
Documentation Browser which is bundled with the C# SDK.
using System;
class NumberDemo{
public static void Main(){
int i = Convert.ToInt32("7B", 16); //
hexadecimal 7B (in base 16) ->
//
decimal 123
Console.WriteLine(i); // 123
Console.WriteLine(123.ToString("X")); //
decimal 123 -> hexadecimal 7B
}
}
// 1111011
Console.WriteLine(r);
foreach (int digit in s) Console.Write("{0} ",
digit); Console.WriteLine();
foreach (int digit in t) Console.Write("{0} ",
digit);
}
Enumerations types Enumeration types provide for symbolic names of selected
Slide Annotated slide Contents Index integer values. Use of enumeration types improves the
References Textbook
readability of your programs.
Enumeration types are similar to each other in C and C#
Program: Two examples of public enum Ranking {Bad, OK, Good}
enumeration types in C#.
public enum OnOff: byte{
On = 1, Off = 0}
• An extension of C enumeration types:
o Enumeration types of several different underlying
types can be defined (not just int)
o Enumeration types inherit a number of methods
from the type System.Enum
o The symbolic enumeration constants can be
printed (not just the underlying number)
o Values, for which no enumeration constant exist,
can be dealt with
Ranking r = Ranking.OK;
Console.WriteLine("Ranking is {0}", r );
Console.WriteLine("Ranking is {0}", r+1);
Console.WriteLine("Ranking is {0}", r+2);
foreach(string s in
Enum.GetNames(typeof(Ranking)))
Console.WriteLine(s);
}
}
Program: Output from the Status is On
program that demonstrates Ranking is OK
enumeration types. Ranking is Good
Ranking is 3
3 defined: False
Good defined: True
2 defined: True
Bad
OK
Good
Exercise 2.5. ECTS Grades Define an enumeration type ECTSGrade of the grades A, B, C,
D, E, Fx and F and associate the Danish 7-step grades 12, 10, 7,
4, 2, 0, and -3 to the symbolic ECTS grades.
o Delegates
As an object-oriented programming language, C# is much
stronger than C when it comes to definition of our own non-
simple types
Arrays and Strings Both arrays and strings are classical types, supported by almost
Slide Annotated slide Contents Index any programming language. Both arrays and strings are
References Textbook
reference types. It means that arrays and strings are accessed
via references.
Both arrays and strings are dealt with as objects in C#
string s3 = @"OOP on
the \n semester ""Dat1/Inf1/SW3""";
Console.WriteLine("\n{0}", s3);
string s4 = "OOP on \n the \\n
semester \"Dat1/Inf1/SW3\"";
Console.WriteLine("\n{0}", s4);
}
Program: Output from the s1 and s2: OOP OOP
string demonstration
program. OOP on
the \n semester "Dat1/Inf1/SW3"
OOP on
the \n semester "Dat1/Inf1/SW3"
The substring is: OOP
Exercise 2.7. Use of array Based on the inspiration from the accompanying example, you
types are in this exercise supposed to experiment with some simple C#
arrays.
Reverse the array, and make sure that the reversing works.
Exercise 2.7. Use of string Based on the inspiration from the accompanying example, you
types are in this exercise supposed to experiment with some simple C#
strings.
• System.Array
• System.String
}
Program: Output from the Is cRef null: True
reference demo program. Is cRef null: False
x and y are (0,0)
x and y are (0,0)
There is no particular complexity in normal C# programs due to
use of references
Structs Structs in C and C# are similar to each other. But structs in C#
Slide Annotated slide Contents Index are extended in several ways compared to C.
References Textbook
p2 = p1;
p2.Mirror();
Console.WriteLine("Point is: ({0},{1})", p2.x,
p2.y);
}
}
Program: Output from the Point is: (-3,-4)
struct demo program.
Program: An extended /* Right, Wrong */
demonstration of structs in
C#. using System;
/*
Point1 p1;
Console.WriteLine(p1.x, p1.y);
*/
Point1 p2;
p2.x = 1.0; p2.y = 2.0;
Console.WriteLine("Point is: ({0},{1})", p2.x,
p2.y);
Point1 p3;
p3 = p2;
Console.WriteLine("Point is: ({0},{1})", p3.x,
p3.y);
p4.Mirror();
Console.WriteLine("Point is: ({0},{1})", p4.x,
p4.y);
}
}
Operators This pages shows an overview of all operators in C#.
Slide Annotated slide Contents Index
References Textbook
Console.WriteLine(a);
Console.WriteLine(b); // Use of unassigned
local variable 'b'
class IfDemo {
/*
if (i){
Console.WriteLine("i is regarded as true");
}
else {
Console.WriteLine("i is regarded as false");
}
*/
if (i != 0){
Console.WriteLine("i is not 0");
}
else {
Console.WriteLine("i is 0");
}
}
}
Program: Demonstrations /* Right, Wrong */
of switch. using System;
class SwitchDemo {
public static void Main(){
int j = 1, k = 1;
/*
switch (j) {
case 0: Console.WriteLine("j is 0");
case 1: Console.WriteLine("j is 1");
case 2: Console.WriteLine("j is 2");
default: Console.WriteLine("j is not 0, 1 or
2");
}
*/
switch (k) {
case 0: Console.WriteLine("m is 0"); break;
case 1: Console.WriteLine("m is 1"); break;
case 2: Console.WriteLine("m is 2"); break;
default: Console.WriteLine("m is not 0, 1 or
2"); break;
}
switch (k) {
case 0: case 1: Console.WriteLine("n is 0
or 1"); break;
case 2: case 3: Console.WriteLine("n is 2
or 3"); break;
case 4: case 5: Console.WriteLine("n is 4
or 5"); break;
default: Console.WriteLine("n is not 1, 2,
3, 4, or 5"); break;
}
class ForeachDemo {
public static void Main(){
foreach(int i in ia)
sum += i;
Console.WriteLine(sum);
}
}
Program: Demonstrations /* Right, Wrong */
of try catch. using System;
class TryCatchDemo {
public static void Main(){
int i = 5, r = 0, j = 0;
/*
r = i / 0;
Console.WriteLine("r is {0}", r);
*/
try {
r = i / j;
Console.WriteLine("r is {0}", r);
} catch(DivideByZeroException e){
Console.WriteLine("r could not be
computed");
}
}
}
Functions On this page we will look at parameter passing techniques. C
Slide Annotated slide Contents Index only supports call by value. Call by reference in C is in reality
References Textbook
call by value passing of pointers. C# offers a variety of
different parameter passing modes. We also discuss
overloaded functions - functions of the same name
distinguished by parameters of different types.
All functions in C# are members of classes or structs
/*
public int Increment(int i){
return i + 1;
}
double myVar3;
OutFunction(out myVar3);
Console.WriteLine("myVar3: {0:f}", myVar3);
// 8.00
double myVar4;
ParamsFunction(out myVar4, 1.1, 2.2, 3.3, 4.4,
5.5); // 16.50
Console.WriteLine("Sum in myVar4: {0:f}",
myVar4);
}
}
Program: Demonstration of using System;
overloaded methods in C#.
public class FunctionDemo {
}
Input and output Input and output (IO) is handled by a number of different
Slide Annotated slide Contents Index classes in C#. In both C and C# there very few traces of IO in
References Textbook
the languages as such.
Output to the screen and input from the keyboard is handled by
the C# Console class
• System.String.Format
• System.Console
• System.Int32
• System.Double
Comments
Slide Annotated slide Contents Index
References Textbook
• Similarities.
o Classes in both C# and Java
o Interfaces in both C# and Java
• Differences.
o Structs in C#, not in Java
o Delegates in C#, not in Java
o Nullable types in C#, not in Java
o Anonymous methods
Other substantial
differences
Slide Annotated slide Contents Index
References Textbook
• Program organization
o No requirements to source file organization in C#
• Exceptions
o No catch or specify requirement in C#
• Nested and local classes
o Classes inside classes are static in C#: No inner
classes like in Java
• Arrays
o Rectangular arrays in C#
• Virtual methods
End Module
Program: Typical overall using System;
program structure of a C#
Program. class SomeClass{
}
The Overall Picture
Slide Annotated slide Contents Index
References Textbook
• Program organization
o Similar: Modul/Class in explicit or implicit
namespace
• Program start
o Similar: Main
• Separation of program parts
o VB: Via line organization
o C#: Via use of semicolons
• Comments
o VB: From an apostrophe to the end of the line
o C#: From // to the end of the line or /* ... */
• Case sensitiveness
o VB: Case insensitive. You are free to make your
own "case choices".
Sub Main()
Dim ch As Char = "A"C ' A character
variable
Dim b As Boolean = True ' A boolean
variable
Dim i As Integer = 5 ' An integer
variable (4 bytes)
Dim s As Single = 5.5F ' A floating
point number (4 bytes)
Dim d As Double = 5.5 ' A floating
point number (8 bytes)
End Sub
End Module
Program: The similar C# using System;
program with a number of
variable declarations. class DeclarationsDemo{
}
Declaration and Types
Slide Annotated slide Contents Index
References Textbook
• Declaration structure
o VB: Variable before type
o C#: Variable after type
• Types provide by the languages
o The same underlying types
Sub Main()
Dim i as Integer = 13 \ 6 ' i becomes
2
Dim r as Integer = 13 Mod 6 ' r becomes
1
Dim d as Double = 13 / 6 ' d becomes
2,16666666666667
Dim p as Double = 2 ^ 10 ' p becomes
1024
End Module
Program: The similar C# using System;
program with a number of class ExpressionsDemo{
expressions and operators.
public static void Main(){
int i = 13 / 6; // i becomes 2
int r = 13 % 6; // r becomes 1
double d = 13.0 / 6; // d becomes
2.16666666666667
double p = Math.Pow(2,10); // p becomes 1024
}
Program: A Visual Basic Option Strict On
Program with expressions Option Explicit On
and operators.
Module ExpressionsDemo
Sub Main()
Dim i as Integer = 2, r as Integer = 1
If i <> 3 Then
Console.WriteLine("OK") ' Writes OK
End If
If Not i = 3 Then
Console.WriteLine("OK") ' Same as
above
End If
End Sub
End Module
Program: The similar C# using System;
program with a number of class ExpressionsDemo{
expressions and operators.
public static void Main(){
int i = 2, r = 1;
if (i != 3) Console.WriteLine("OK"); //
Writes OK
if (!(i == 3)) Console.WriteLine("OK"); //
Same as above
}
}
Program: A Visual Basic Option Strict On
Program with expressions Option Explicit On
and operators.
Module ExpressionsDemo
Sub Main()
Dim i as Integer = 2, r as Integer = 1
if (i == 3 && r == 1)
Console.WriteLine("Wrong");
else
Console.WriteLine("OK");
if (i == 3 || r == 1)
Console.WriteLine("OK");
else
Console.WriteLine("Wrong");
}
}
Expressions and
Operators
Slide Annotated slide Contents Index
References Textbook
• Operator Precedence
• Operator precedence
in C#
• VB operator
precedence
• Equality and Assignment
o VB: Suffers from the choice of using the same
operator symbol = for both equality and
assignment
o VB: The context determines the meaning of the
operator symbol =
o C#: Separate equality operator == and assignment
operator =
• Remarkable operators
o VB: Mod, &, \, And, AndAlso, Or, OrElse
o C#: ==, !, %, ?:
Control Structures for
Selection
Slide Annotated slide Contents Index
References Textbook
Program: A Visual Basic Module IfDemo
Program with an If Then
Else control structure. Sub Main()
Dim i as Integer, res as Integer
i = Cint(InputBox("Type a number"))
If i < 0 Then
res = -1
Console.WriteLine("i is negative")
Elseif i = 0
res = 0
Console.WriteLine("i is zero")
Else
res = 1
Console.WriteLine("i is positive")
End If
Console.WriteLine(res)
End Sub
End Module
Program: The similar C# using System;
program with an if else
control structure. class IfDemo{
if (i < 0){
res = -1;
Console.WriteLine("i is negative");
}
else if (i == 0) {
res = 0;
Console.WriteLine("i is zero");
}
else {
res = 1;
Console.WriteLine("i is positive");
}
Console.WriteLine(res);
}
}
Program: A Visual Basic Module IfDemo
Program with a Select
control structure. Sub Main()
Dim month as Integer = 2
Dim numberOfDays as Integer
switch(month){
case 1: case 3: case 5: case 7: case 8: case
10: case 12:
numberOfDays = 31; break;
case 4: case 6: case 9: case 11:
numberOfDays = 30; break;
case 2:
numberOfDays = 28; break; // or 29
default:
throw new Exception("Problems");
}
Console.WriteLine(numberOfDays); // prints 28
}
}
Control structures for
Selection
Slide Annotated slide Contents Index
References Textbook
• If-then-else
o Similar in the two languages
• Case
o C#: Efficient selection of a single case - via
underlying jumping
o VB: Sequential test of cases - the first matching
case is executed
o VB: Select Case approaches the expressive power
of an if-then-elseif-else chain
For i as Integer = 1 To 10
sum = sum + i
Next i
Sub Main()
Const PI As Double = 3.14159
Dim radius As Double, area As Double
Do
radius = Cdbl(InputBox("Type radius"))
If radius < 0 Then
Exit Do
End If
area = PI * radius * radius
Console.WriteLine(area)
Loop
End Sub
End Module
Program: The similar C# using System;
program with a similar class ForDemo{
for and a break.
public static void Main(){
const double PI = 3.14159;
double radius, area;
for(;;){
radius = double.Parse(Console.ReadLine());
if (radius < 0) break;
area = PI * radius * radius;
Console.WriteLine(area);
}
}
}
Control structures for
iteration
Slide Annotated slide Contents Index
References Textbook
• While
o Very similar in C# and VB
o C#: Does also support a do ... while
• Do Loop
o VB: Elegant, powerful, and symmetric.
o No direct counterpart in C#
• For
o C#: The for loop is very powerful.
Sub Main()
Dim table(9) as Integer ' indexing from 0 to
9.
For i as Integer = 0 To 9
table(i) = i * i
Next
For i as Integer = 0 To 9
Console.WriteLine(table(i))
Next
End Sub
End Module
Program: The similar C# using System;
program with an array of
10 elements. class ArrayDemo{
• Notation
o VB: a(i)
o C#: a[i]
• Range
o Both from zero to an upper limit
o VB: The highest index is given in an array
variable declaration
Sub Main()
Dim someNumbers(9) as Integer
Dim theSum as Integer = 0
For i as Integer = 0 To 9
someNumbers(i) = i * i
Next
Sum(someNumbers, theSum)
Console.WriteLine(theSum)
End Sub
End Module
Program: The similar C# using System;
program with void class ProcedureDemo{
method.
public static void Sum(int[] table, ref int
result){
result = 0;
for(int i = 0; i <= 9; i++)
result += table[i];
}
Sub Main()
Dim someNumbers(9) as Integer
Dim theSum as Integer = 0
For i as Integer = 0 To 9
someNumbers(i) = i * i
Next
theSum = Sum(someNumbers)
Console.WriteLine(theSum)
End Sub
End Module
Program: The similar C# using System;
program with int method. class ProcedureDemo{
theSum= Sum(someNumbers);
Console.WriteLine(theSum);
}
}
Procedures and
Functions
Slide Annotated slide Contents Index
References Textbook
• Procedures
o VB: Subprogram
o C#: void method (void function)
• Functions
o VB: Functions
o C#: int method or someType method
• Parameter passing
public Die(){
randomNumberSupplier = new
Random(unchecked((int)DateTime.Now.Ticks));
numberOfEyes = NewTossHowManyEyes();
}
Sub Main()
Dim D1 as new Die()
Dim D2 as new Die()
D1.Toss()
Console.WriteLine(D1)
Console.WriteLine()
For i as Integer = 1 To 10
D2.Toss()
Console.WriteLine(D2)
Next i
End Sub
End Module
Program: Compilation and csc /t:library die.cs
execution. vbc /r:die.dll client.vb
client
Object-oriented
programming in
Visual Basic
Slide Annotated slide Contents Index
References Textbook
• C# Express Video
Lectures
Only on Windows...
C# Tools on Unix
Slide Annotated slide Contents Index
References Textbook