Você está na página 1de 40

Chapter 2

Introduction to C#
Kurt Nørmark ©
Department of Computer Science, Aalborg University,
Denmark

The C# Language and


System

C# seen in a historic
perspective
Slide Annotated slide Contents Index
References Textbook

C# has been inspired by earlier object-oriented programming


languages
• Simula (1967)
o The very first object-oriented programming
language
• C++ (1983)
o The first object-oriented programming language in
the C family of languages
• Java (1995)
o Sun's object-oriented programming language
• C# (2001)

o Microsoft's object-oriented programming language


Reference

• Computer Language
History
The Common
Language
Infrastructure
Slide Annotated slide Contents Index
References Textbook

The Common Language Infrastructure (CLI) is a specification


that allows several different programming languages to be used
together on a given platform
• Parts of the Common Language Infrastructure:
o Common Intermediate language (CIL) including a
common type system (CTS)
o Common Language Specification (CLS) - shared
by all languages
o Virtual Execution System (VES)

o Metadata about types, dependent libraries,


attributes, and more
MONO and .NET are both implementations of the Common
Language Infrastructure

The C# language and the Common Language Infrastructure are


standardized by ECMA and ISO
CLI Overview from
Wikipedia
Slide Annotated slide Contents Index
References Textbook
Figure. Wikipedia's
overview diagram of the
CLI

C# Compilation and
Execution
Slide Annotated slide Contents Index
References Textbook

The Common Language Infrastructure supports a two-step


compilation process
• Compilation
o The C# compiler: Translation of C# source to CIL
o Produces .dll and .exe files
oJust in time compilation: Translation of CIL to
machine code
• Execution
o With interleaved Just in Time compilation
o On Mono: Explicit activation of the interpreter

o On Window: Transparent activation of the


interpreter
.dll and .exe files are - with some limitations - portable in
between different platforms
C# in relation to C
Simple types This page is about integers, real numbers, characters, and
Slide Annotated slide Contents Index booleans.
References Textbook

Most simple types in C# are similar to the simple types in C


• Major differences:
o All simple C# types have fixed bit sizes
o C# has a boolean type called bool
o C# chars are 16 bit long
o In C# there is a high-precision 128 bit numeric
fixed-point type called decimal
o Pointers are not supported in the normal parts of a
C# program
 In the unsafe part C# allows for pointers
like in C

o All simple types are in reality structs in C#, and


therefore they have members

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;

Console.WriteLine("ch1 is a letter: {0}",


char.IsLetter(ch1));

Console.WriteLine("{0} {1} {2}", ch3, ch4,


char.ToLower(ch5));

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);

ushort us1 = ushort.MinValue; //


Unsigned 16 bit integer
System.UInt16 us2= System.UInt16.MaxValue;
Console.WriteLine("ushort: {0} : {1}", us1,
us2);

int i1 = int.MinValue; //
Signed 32 bit integer
System.Int32 i2 = System.Int32.MaxValue;
Console.WriteLine("int: {0} : {1}", i1, i2);

uint ui1 = uint.MinValue; //


Unsigned 32 bit integer
System.UInt32 ui2= System.UInt32.MaxValue;
Console.WriteLine("uint: {0} : {1}", ui1, ui2);

long l1 = long.MinValue; //
Signed 64 bit integer
System.Int64 l2 = System.Int64.MaxValue;
Console.WriteLine("long: {0} : {1}", l1, l2);

ulong ul1 = ulong.MinValue; //


Unsigned 64 bit integer
System.UInt64 ul2= System.UInt64.MaxValue;
Console.WriteLine("ulong: {0} : {1}", ul1,
ul2);

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);

decimal dm1 = decimal.MinValue; // 128


bit fixed-point
System.Decimal dm2= System.Decimal.MaxValue;
Console.WriteLine("decimal: {0} : {1}", dm1,
dm2);

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.

Locate the type System.Char in your C# documentation and


take a look at the methods available on characters.

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.

Along the line of the character demo program above, write a


small C# program that uses the char predicates IsDigit,
IsPunctuation, and IsSeparator.

It may be useful to find the code position - also known as the


code point - of a character. As an example, the code position of
'A' is 65. Is there a method in System.Char which gives access
to this information? If not, can you find another way to find the
code position of a character?

Be sure to understand the semantics (meaning) of the method


GetNumericValue in type Char.
Exercise 2.3. In this exercise we will write a program that can convert between
Hexadecimal numbers decimal and hexadecimal notation of numbers. Please consult the
focus boxes about hexadecimal numbers in the text book version
if you need to.

You might expect that this functionality is already present in the


C# libraries. And to some degree, it is.

The static method ToInt32(string, Int32) in class Convert


converts the string representation of a number (the first parameter)
to an arbitrary number system (the second parameter). Similar
methods exist for other integer types.

The method ToString(string) in the struct Int32, can be used


for conversion from an integer to a hexadecimal number,
represented as a string. The parameter of ToString is a format
string. If you pass the string "X" you get a hexadecimal number.

The program below shows examples:

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
}
}

Now, write a method which converts a list (or array) of digits in


base 16 (or more generally, base b, b >= 2) to a decimal number.

The other way around, write a method which converts a positive


decimal integer to a list (or array) of digits in base 16 (or more
generally, base b).

Here is an example where the requested methods are used:

public static void Main(){


int r = BaseBToDecimal(16, new List{7, 11}); //
7B -> 123
List s = DecimalToBaseB(16, 123); //
123 -> {7, 11} = 7B
List t = DecimalToBaseB(2, 123); //
123 -> {1, 1, 1, 1, 0, 1, 1 } =

// 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

o Combined enumerations represent a collection of


enumerations
Program: Demonstration using System;
of enumeration types in
C#. Programming with class NonSimpleTypeDemo{
Ranking and OnOff.
public enum Ranking {Bad, OK, Good}

public enum OnOff: byte{


On = 1, Off = 0}

public static void Main(){


OnOff status = OnOff.On;
Console.WriteLine();
Console.WriteLine("Status is {0}", status);

Ranking r = Ranking.OK;
Console.WriteLine("Ranking is {0}", r );
Console.WriteLine("Ranking is {0}", r+1);
Console.WriteLine("Ranking is {0}", r+2);

bool res1 = Enum.IsDefined(typeof(Ranking), 3);


Console.WriteLine("{0} defined: {1}", 3, res1);

bool res2= Enum.IsDefined(typeof(Ranking),


Ranking.Good);
Console.WriteLine("{0} defined: {1}",
Ranking.Good , res2);

bool res3= Enum.IsDefined(typeof(Ranking), 2);


Console.WriteLine("{0} defined: {1}", 2 ,
res3);

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.

What is the most natural underlying type of ECTSGrade?

Write a small program which illustrates how to use the new


enumeration type.
Exercise 2.5. Use of Consult the documentation of type type System.Enum, and get a
Enumeration types general overview of the methods in this struct.

Be sure that you are able to find the documentation of


System.Enum

Test drive the example EnumTest, which is part of MicroSoft's


documentation. Be sure to understand the program relative to
its output.

Write your own program with a simple enumeration type. Use


the Enum.CompareTo method to compare two of the values of
your enumeration type.
Non-simple types This is about arrays, strings, structs. All the classes and structs
Slide Annotated slide Contents Index that we program ourselves also count as non-simple types.
References Textbook

C# allows for a variety of non-simple types, most important


Classes
• Similarities
o Arrays in C#: Indexed from 0. Jagged arrays -
arrays of arrays
o Strings in C#: Same notation as in C, and similar
escape characters

o Structs in C#: A value type like in C.


• Differences
o Arrays: Rectangular arrays in C#
o Strings: No \0 termination in C#

o Structs: Much expanded in C#. Structs can have


methods.
• New kinds of non-simple types in C#:
o Classes
o Interfaces

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#

In addition, there is special notation in the C# language of arrays


and strings
• Similarities

o C# and C have similar syntaxes for arrays and


strings
• Differences
o Arrays in C# can be rectangular or jagged (arrays
of arrays)
o In C#, an array is not a pointer to the first element
o Index out of bound checking is done in C#
o Strings are immutable in C#, but not in C

o In C# there are two kinds of string literals: "a


string\n" and @"a string\n"
Program: Demonstrations
of array types in C#.
Program: Output from the Array lengths. a1:3 b2:8 c1:2
array demonstration Lenght of a2: 10
program. Sorting a1:
a
bb
ccc
Program: A demonstration using System;
of strings in C#.
class ArrayStringDemo{

public static void Main(){


string s1 = "OOP";
System.String s2 = "\u004f\u004f\u0050"; //
equivalent
Console.WriteLine("s1 and s2: {0} {1}", s1,
s2);

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);

string s5 = "OOP E06".Substring(0,3);


Console.WriteLine("The substring is: {0}",
s5);
}

}
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.

First, consult the documentation of the class System.Array.


Please notice the properties and methods that are available on
arrays in C#.

Declare, initialize, and print an array of names (e.g. array of


strings) of all members of your group.

Sort the array, and search for a given name using


System.Array.BinarySearch method.

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.

First, consult the documentation of the class System.String -


either in your documentation browser or at
msdn.microsoft.com. Read the introduction (remarks) to string
which contains useful information! There exists a large variety
of operations on strings. Please make sure that you are aware of
these. Many of them will help you a lot in the future!

Make a string of your own first name, written with escaped


Unicode characters (like we did for "OOP" in the accompanying
example). If necessary, consult the unicode code charts (Basic
Latin and Latin-1) to find the appropriate characters.
Take a look at the System.String.Insert method. Use this
method to insert your last name in the first name string. Make
your own observations about Insert relative to the fact that
strings in C# are immutable.
In C# it is often more attractive to use a (type parameterized)
collection class instead of an array
References

• System.Array

• System.String

Pointers and References are important in C#. A reference is similar to a


references point in C, but references are much easier to work with.
Slide Annotated slide Contents Index References can be passed around (via parameters). Objects are
References Textbook
always accessed via references, but in contrast to C, the
following of a references happens implicitly, and
automatically.
References in C# can be understood as a very restricted notion of
pointers, as known from C programming
• Pointers
o In normal C# programs: Pointers are not used
 All the complexity of pointers, pointer
arithmetic, dereferencing, and the address
operator is not found in normal C#
programs
o In specially marked unsafe sections: Pointers can
be used almost as in C.
 Do not use them in your C# programs!
• References
o Objects (instance of classes) are always accessed
via references in C#
o References are automatically dereferenced in C#

o There are no particular operators in C# that are


related to references
Program: Demonstrations using System;
of references in C#.
public class C {
public double x, y;
}

public class ReferenceDemo {

public static void Main(){


C cRef, anotherCRef;
cRef = null;
Console.WriteLine("Is cRef null: {0}", cRef ==
null);

cRef = new C();


Console.WriteLine("Is cRef null: {0}", cRef ==
null);

Console.WriteLine("x and y are ({0},{1})",


cRef.x, cRef.y);
anotherCRef = F(cRef);
}

public static C F(C p){


Console.WriteLine("x and y are ({0},{1})",
p.x, p.y);
return p;
}

}
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

The concept of structs has been much extended in C#


• Similarities
o Structs in C# can be used almost in the same way
as structs in C
o Structs are value types in both C and C#
• Differences
o Structs in C# are almost as powerful as classes
 Structs in C# can have operations
(methods) in the same way as classes

 Structs in C# cannot inherit from other


structs or classes
Program: Demonstrations using System;
of structs in C#.
public struct Point {
public double x, y;
public Point(double x, double y){this.x = x;
this.y = y;}
public void Mirror(){x = -x; y = -y;}
} // end Point

public class StructDemo{

public static void Main(){


Point p1 = new Point(3.0, 4.0),
p2;

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;

public struct Point1 {


public double x, y;
}

public struct Point2 {


public double x, y;
public Point2(double x, double y){this.x = x;
this.y = y;}
public void Mirror(){x = -x; y = -y;}
}

public class StructDemo{

public static void Main(){

/*
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);

Point2 p4 = new Point2(3.0, 4.0);

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

Most operators in C are also found in C#


Table. The operator Level Category Operators Associativity
priority table of C#. (binary/tertiary)
Operators with high level
numbers have high 14 Primary x.y f(x) a[x] left to right
priorities. In a given x++ x-- new
expression, operators of typeof checked
high priority are unchecked default
evaluated before delegate
operators with lower 13 Unary + - ! ~ ++x left to right
priority. The associativity --x (T)x true
tells if operators at the
false sizeof
same level are evaluated
from left to right or from 12 Multiplicative * / % left to right
right to left. 11 Additive + - left to right
10 Shift << >> left to right
9 Relational and Type < <= > >= is left to right
testing as
8 Equality == != left to right
7 Logical/bitwise and & left to right
6 Logical/bitwise xor ^ left to right
5 Logical/bitwise or | left to right
4 Conditional and && left to right
3 Conditional or || left to right
2 Null coalescing ?? left to right
1 Conditional ?: right to left
0 Assignment or = *= /= %= += right to left
Lambda expression -= <<= >>= &=
^= |= =>
Reference

• Similar table for C


It is possible to overload many of the C# operators

This allows for terse and convenient notation in many classes


Commands and On this page we discuss control structures for selection and
Control Structures iteration. As usual, we concentrate on the differences between
Slide Annotated slide Contents Index C an C#.
References Textbook
Almost all control structures in C can be used the same way in
C#
• Similarities
o Expression statements, such as a = a + 5;
o Blocks, such as {a = 5; b = a;}

o if, if-else, switch, for, while, do-while,


return, break, continue, and goto in C# are all
similar to C
• Differences
o The C# foreach loop provides for easy traversal
of all elements in a collection
o try-catch-finally and throw in C# are related
to exception handling

o Some more specialized statements have been


added: checked, unchecked, using, lock and
yield.
Program: Demonstrations using System;
of definite assignment.
class DefiniteAssignmentDemo{

public static void Main(){


int a, b;
bool c;

if (ReadFromConsole("Some Number") < 10){


a = 1; b = 2;
} else {
a = 2;
}

Console.WriteLine(a);
Console.WriteLine(b); // Use of unassigned
local variable 'b'

while (a < b){


c = (a > b);
a = Math.Max(a, b);
}

Console.WriteLine(c); // Use of unassigned


local variable 'c'

public static int ReadFromConsole(string prompt){


Console.WriteLine(prompt);
return int.Parse(Console.ReadLine());
}
}
Program: Demonstrations /* Right, Wrong */
of if. using System;

class IfDemo {

public static void Main(){


int i = 0;

/*
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;
}

string str = "two";


switch (str) {
case "zero": Console.WriteLine("str is 0");
break;
case "one": Console.WriteLine("str is 1");
break;
case "two": Console.WriteLine("str is 2");
break;
default: Console.WriteLine("str is not 0, 1
or 2"); break;
}
}
}
Program: Demonstrations /* Right, Wrong */
of foreach. using System;

class ForeachDemo {
public static void Main(){

int[] ia = {1, 2, 3, 4, 5};


int sum = 0;

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

C# supports are variety of different function members: methods,


properties, events, indexers, operators, and constructors
• Similarities

o The basic ideas of function definition and function


call are the same in C and C#
• Differences
o Several different parameter passing techniques in
C#
 Call by value. For input. No modifier.
 Call by reference. For input and output or
output only
 Input and output: Modifier ref
 Output: Modifier out
 Modifiers used both with formal and
actual parameters
o Functions with a variable number of input
parameters in C# (cleaner than in C)
o Overloaded function members in C#

o First class functions (delegates) in C#


Program: Demonstration of /* Right, Wrong */
simple functions in C#.
using System;

/*
public int Increment(int i){
return i + 1;
}

public void Main (){


int i = 5,
j = Increment(i);
Console.WriteLine("i and j: {0}, {1}", i, j);
} // end Main
*/

public class FunctionDemo {


public static void Main (){
SimpleFunction();
}

public static void SimpleFunction(){


int i = 5,
j = Increment(i);
Console.WriteLine("i and j: {0}, {1}", i, j);
}

public static int Increment(int i){


return i + 1;
}
}
Program: Demonstration of using System;
parameter passing in C#. public class FunctionDemo {

public static void Main (){


ParameterPassing();
}

public static void ValueFunction(double d){


d++;}

public static void RefFunction(ref double d){


d++;}

public static void OutFunction(out double d){


d = 8.0;}

public static void ParamsFunction(out double res,


params double[]
input){
res = 0;
foreach(double d in input) res += d;
}

public static void ParameterPassing(){


double myVar1 = 5.0;
ValueFunction(myVar1);
Console.WriteLine("myVar1: {0:f}", myVar1);
// 5.00

double myVar2 = 6.0;


RefFunction(ref myVar2);
Console.WriteLine("myVar2: {0:f}", myVar2);
// 7.00

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 {

public static void Main (){


Overloading();
}

public static void F(int p){


Console.WriteLine("This is F(int) on {0}", p);
}

public static void F(double p){


Console.WriteLine("This is F(double) on {0}",
p);
}

public static void F(double p, bool q){


Console.WriteLine("This is F(double,bool) on
{0}, {1}", p, q);
}

public static void F(ref int p){


Console.WriteLine("This is F(ref int) on {0}",
p);
}

public static void Overloading(){


int i = 7;

F(i); // This is F(int) on 7


F(5.0); // This is F(double) on 5
F(5.0, false); // This is F(double,bool) on
5, False
F(ref i); // This is F(ref int) on 7
}

}
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

File IO is handled by various Stream classes in C#


• Similarities
o Console.Write and Console.WriteLine in C#
correspond to printf in C
• Differences
o There is no direct counterpart to C's scanf in C#

o Comprehensive formatting support of DateTime


objects in C#
Program: /* Right, Wrong */
Demonstrations of
Console output in C#. using System;
public class OutputDemo {

// Placeholder syntax: {<argument#>[,<width>]


[:<format>[<precision>]]}

public static void Main(){


Console.Write( "Argument number only: {0}
{1}\n", 1, 1.1);
// Console.WriteLine("Formatting code d: {0:d},
{1:d}", 2, 2.2);

Console.WriteLine("Formatting codes d and f: {0:d}


{1:f}", 3, 3.3);
Console.WriteLine("Field width: {0,10:d}
{1,10:f}", 4, 4.4);
Console.WriteLine("Left aligned: {0,-10:d} {1,-
10:f}", 5, 5.5);
Console.WriteLine("Precision: {0,10:d5}
{1,10:f5}", 6, 6.6);
Console.WriteLine("Exponential: {0,10:e5}
{1,10:e5}", 7, 7.7);
Console.WriteLine("Currency: {0,10:c2}
{1,10:c2}", 8, 8.887);
Console.WriteLine("General: {0:g} {1:g}", 9,
9.9);
Console.WriteLine("Hexadecimal: {0:x5}", 12);

Console.WriteLine("DateTime formatting with F:


{0:F}", DateTime.Now);
Console.WriteLine("DateTime formatting with G:
{0:G}", DateTime.Now);
Console.WriteLine("DateTime formatting with T:
{0:T}", DateTime.Now);
}
}
Program: Output from the Argument number only: 1 1,1
output demo program. Formatting codes d and f: 3 3,30
Field width: 4 4,40
Left aligned: 5 5,50
Precision: 00006 6,60000
Exponential: 7,00000e+000 7,70000e+000
Currency: kr 8,00 kr 8,89
General: 9 9,9
Hexadecimal: 0000c
DateTime formatting with F: 4. juli 2008 15:35:31
DateTime formatting with G: 04-07-2008 15:35:31
DateTime formatting with T: 15:35:31
Program: Demonstrations /* Right, Wrong */
of Console input in C#.
using System;
public class InputDemo {

public static void Main(){


Console.Write("Input a single character: ");
char ch = (char)Console.Read();
Console.WriteLine("Character read: {0}", ch);
Console.ReadLine();

Console.Write("Input an integer: ");


int i = int.Parse(Console.ReadLine());
Console.WriteLine("Integer read: {0}", i);

Console.Write("Input a double: ");


double d = double.Parse(Console.ReadLine());
Console.WriteLine("Double read: {0:f}", d);
}
}
Program: A sample dialog Input a single character: a
with the Console IO demo Character read: a
program. Input is shown in Input an integer: 123
bold style. Boldface items Integer read: 123
represent the input entered Input a double: 456,789
by the user of the program. Double read: 456,79
References

• System.String.Format

• System.Console

• System.Int32

• System.Double

Comments
Slide Annotated slide Contents Index
References Textbook

C# supports two different kinds of comments and XML variants


of these
• Single-line comments like in C++
// This is a single-line comment
• Delimited comments like in C
/* This is a delimited comment */
• XML single-line comments:
/// <summary> This is a single-line XML
comment </summary>

• XML delimited comments:


/** <summary> This is a delimited XML comment
</summary> */

XML comments can only be given before declarations, not


inside other fragments

Delimited comments cannot be nested


C# in relation to Java
C# versus Java
Slide Annotated slide Contents Index
References Textbook

With respect to the basic language constructs, C# and Java are


very close to each other
• Types
o Richer repertoire in C# than in Java
• Operations

o Richer repertoire in C# than in Java


Strong overall similarities - Different with respect to a lot of
details
Types
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 Class-like Enumeration types in Java; Simpler


approach in C#
Operations
Slide Annotated slide Contents Index
References Textbook

• Similarities: Operations in both Java and C#


o Methods
• Differences: Operations only in C#
o Properties
o Indexers
o Overloaded operators

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

o Virtual as well as non-virtual methods in C#


C# in relation to
Visual Basic
The Overall Picture
Slide Annotated slide Contents Index
References Textbook
Program: Typical overall Module MyModule
program structure of a
Visual Basic Program. Sub Main()
Dim name As String ' A variable name of
type string
name = InputBox("Type your name")
MsgBox("Hi, your name is " & name)
End Sub

End Module
Program: Typical overall using System;
program structure of a C#
Program. class SomeClass{

public static void Main(){


string name; // A variable name of type
string
Console.WriteLine("Type your name");
name = Console.ReadLine();
Console.WriteLine("Hi, your name is " + name);
}

}
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".

o C#: Case sensitive. You must use the correct case


for both keywords and you must be "case
consistent" with respect to names.
Declarations and
Types
Slide Annotated slide Contents Index
References Textbook
Program: A Visual Basic Option Strict On
Program with a number of Option Explicit On
variable declarations.
Module DeclarationsDemo

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{

public static void Main(){


char ch = 'A'; // A character
variable
bool b = true; // A boolean variable
int i = 5; // An integer variable
(4 byges)
float s = 5.5F; // A floating point
number (4 bytes)
double d = 5.5 ; // A floating point
number (8 bytes)
}

}
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

o Known under slightly different names in VB and


C#
VB and C# share the .NET types
Expressions and
Operators
Slide Annotated slide Contents Index
References Textbook
Program: A Visual Basic Option Strict On
Program with expressions Option Explicit On
and operators.
Module ExpressionsDemo

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

' Dim b as Boolean i = 3 ' Illegal -


Compiler error
Dim b as Boolean, c as Boolean ' b and c
are false (default values)
c = b = true ' TRICKY: c
becomes false
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 = 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

bool b = i == 3; // b becomes false


bool c = b = true; // both b and c
become true
}

}
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 AndAlso r = 1 Then ' Writes OK


Console.WriteLine("Wrong")
Else
Console.WriteLine("OK")
End If
If i = 3 OrElse r = 1 Then ' Writes OK
Console.WriteLine("OK")
Else
Console.WriteLine("Wrong")
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 && 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

o Major differences between the two languages


References

• 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{

public static void Main(){


int i, res;
i = Int32.Parse(Console.ReadLine());

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

Select Case month


Case 1, 3, 5, 7, 8, 10, 12
numberOfDays = 31
Case 4, 6, 9, 11
numberOfDays = 30
Case 2
numberOfDays = 28 ' or 29
Case Else
Throw New Exception("Problems")
End Select

Console.WriteLine(numberOfDays) ' prints 28


End Sub
End Module
Program: The similar C# using System;
program with a switch
control structure. class CaseDemo{

public static void Main(){


int month = 2,
numberOfDays;

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

o Case "fall through" is disallowed in both


languages
Control Structures for
Iteration
Slide Annotated slide Contents Index
References Textbook
Program: A Visual Basic Module WhileDemo
Program with a while
loop. Sub Main()
Dim large As Integer = 106, small As Integer
= 30
Dim remainder As Integer

While small > 0


remainder = large Mod small
large = small
small = remainder
End While

Console.WriteLine("GCD is {0}", large) '


Prints 2
End Sub
End Module
Program: The similar C# using System;
program with a while loop. class WhileDemo{

public static void Main(){


int large = 106, small = 30, remainder;

while (small > 0){


remainder = large % small;
large = small;
small = remainder;
}

Console.WriteLine("GCD is {0}", large); //


Prints 2
}
}
Program: A Visual Basic Module ForDemo
Program with a for loop.
Sub Main()
Dim sum As Integer = 0

For i as Integer = 1 To 10
sum = sum + i
Next i

Console.WriteLine("The sum is {0}", sum) '


Prints 55
End Sub
End Module
Program: The similar C# using System;
program with a for loop. class ForDemo{

public static void Main(){


int sum = 0;

for(int i = 1; i <= 10; i++)


sum = sum + i;

Console.WriteLine("The sum is {0}", sum); //


Prints 55
}
}
Program: A Visual Basic Option Strict On
Program with a Do Loop. Option Explicit On
Module DoDemo

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.

o VB: Similar to classical for loop from Algol and


Pascal
Arrays
Slide Annotated slide Contents Index
References Textbook
Program: A Visual Basic Option Strict On
Program with an array of Option Explicit On
10 elements. Module ArrayDemo

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{

public static void Main(){


int[] table = new int[10]; // indexing from 0
to 9

for(int i = 0; i <= 9; i++)


table[i] = i * i;

for(int i = 0; i <= 9; i++)


Console.WriteLine(table[i]);
}
}
Arrays
Slide Annotated slide Contents Index
References Textbook

• 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

o C#: The length of the array is given in an array


variable declaration
Procedures and
Functions
Slide Annotated slide Contents Index
References Textbook
Program: A Visual Basic Option Strict On
Program with a procedure Option Explicit On
- Subprogram. Module ArrayDemo

Sub Sum(ByVal table() As Integer, ByRef result


as Integer)
result = 0
For i as Integer = 0 To 9
result += table(i)
Next
End Sub

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];
}

public static void Main(){


int[] someNumbers = new int[10];
int theSum = 0;

for(int i = 0; i <= 9;i++)


someNumbers[i] = i * i;

Sum(someNumbers, ref theSum);


Console.WriteLine(theSum);
}
}
Program: A Visual Basic Option Strict On
Program with a function. Option Explicit On
Module ArrayDemo

Function Sum(ByVal table() As Integer) as


Integer
Dim result as Integer = 0
For i as Integer = 0 To 9
result += table(i)
Next
return result
End Function

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{

public static int Sum(int[] table){


int result = 0;
for(int i = 0; i <= 9; i++)
result += table[i];
return result;
}

public static void Main(){


int[] someNumbers = new int[10];
int theSum = 0;

for(int i = 0; i <= 9;i++)


someNumbers[i] = i * i;

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

o Both languages support call by value and call by


reference
Combined C# and
Visual Basic
Programming
Slide Annotated slide Contents Index
References

A client written in Visual Basic and a server written in C#


Program: A class Die using System;
programmed in C#.
public class Die {
private int numberOfEyes;
private Random randomNumberSupplier;
private const int maxNumberOfEyes = 6;

public Die(){
randomNumberSupplier = new
Random(unchecked((int)DateTime.Now.Ticks));
numberOfEyes = NewTossHowManyEyes();
}

public void Toss(){


numberOfEyes = NewTossHowManyEyes();
}

private int NewTossHowManyEyes (){


return
randomNumberSupplier.Next(1,maxNumberOfEyes + 1);
}

public int NumberOfEyes() {


return numberOfEyes;
}

public override String ToString(){


return String.Format("[{0}]", numberOfEyes);
}
}
Program: A client of class Imports System
Die programmed in Visual
Basic. Module DieApplication

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

Both VB and C# supports object-oriented programming on


the .Net platform
C# Tools and IDEs
C# Tools on Windows
Slide Annotated slide Contents Index
References Textbook

Microsoft supplies several different set of tools that support the


C# programmer
• .NET Framework SDK 3.5
o "Software Development Kit"
o Command line tools, such as the C# compiler csc
• Visual C# Express
o IDE - An Integrated Development Environment
o A C# specialized, free version of Microsoft Visual
Studio 2008
• Visual Studio
o IDE - An Integrated Development Environment

o The professional, commercial development


environment for C# and other programming
languages
Reference

• C# Express Video
Lectures
Only on Windows...
C# Tools on Unix
Slide Annotated slide Contents Index
References Textbook

The MONO project provides tools for C# development on


Linux, Solaris, Mac OS X, Windows, and Unix.
• MONO
o An open source project (sponsored by Novell)
o Corresponds the the Microsoft SDK
o Based on ECMA specifications of C# and the
Common Language Infrastructure (CLI) Virtual
Machine
o Command line tools
o Compilers: mcs (C# 1.5) and gmcs (C# 2.0)
• MONO on cs.aau.dk
o Mono is already installed on the application
servers at cs.aau.dk
• MONO on your own Linux machine
o You can install MONO yourself if you wish
• MonoDevelop

o A GNOME IDE for C#


MONO is not as updated as the Microsoft C# solutions
Documentation Tools
Slide Annotated slide Contents Index
References Textbook

It is important to have access to documentation of the C#


standard class library
• Local documentation
o The SDK 3.5 comes with a special documentation
browser
o Visual C# Express has integrated documentation
available
• Documentation from a Microsoft webserver

o Link from the course home page - C# resources


Collected references Computer Language History
Contents Index
The struct System.Decimal
The struct System.Double
The struct System.Single
The struct System.UInt64
The struct System.Int64
The struct System.UInt32
The struct System.Int32
The struct System.UInt16
The struct System.Int16
The struct System.Byte
The struct System.Sbyte
Decimal Floating Point in .NET
The struct System.Char
System.Enum
System.String
System.Array
Similar table for C
System.Double
System.Int32
System.Console
System.String.Format
VB operator precedence
Operator precedence in C#
C# Express Video Lectures

Você também pode gostar