View
287
Download
0
Category
Tags:
Preview:
Citation preview
Chapter 2Introduction to C#Kurt Nørmark ©Department of Computer Science, Aalborg University, Denmark
The C# Language and System
C# seen in a historic perspectiveSlide Annotated slide Contents IndexReferences 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 InfrastructureSlide Annotated slide Contents IndexReferences 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 languageso 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 WikipediaSlide Annotated slide Contents IndexReferences Textbook
Figure. Wikipedia's overview diagram of the CLI
C# Compilation and ExecutionSlide Annotated slide Contents IndexReferences Textbook
The Common Language Infrastructure supports a two-step compilation process
Compilationo The C# compiler: Translation of C# source to CILo Produces .dll and .exe files
o Just in time compilation: Translation of CIL to machine code
Executiono With interleaved Just in Time compilationo 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 typesSlide Annotated slide Contents IndexReferences Textbook
This page is about integers, real numbers, characters, and booleans.
Most simple types in C# are similar to the simple types in C
Major differences:o All simple C# types have fixed bit sizeso C# has a boolean type called boolo C# chars are 16 bit longo In C# there is a high-precision 128 bit numeric
fixed-point type called decimalo 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 of the simple type bool in C#. Shows boolean constants and how to deal with the default boolean value (false).
using System;
class BoolDemo{
public static void Main(){ bool b1, b2; b1 = true; b2 = default(bool); Console.WriteLine("The value of b2 is {0}", b2); // False }
}
Program: Demonstrations of the simple type char in
using System;
C#. Illustrates character constants, hexadecimal escape notation, and character methods.
class CharDemo{
public static void Main(){ 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.GetNumericValue('a')); }
}
Program: Demonstrations of numeric types in C#. Illustrates all numeric types in C#. Exercises minimum and maximum values of the numeric types.
using System;using System.Globalization;
class NumberDemo{
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 numeric demo program. Output from the program above. Reveals minimum and maximum values of all the numeric types.
sbyte: -128 : 127byte: 0 : 255short: -32768 : 32767ushort: 0 : 65535int: -2147483648 : 2147483647uint: 0 : 4294967295long: -9223372036854775808 : 9223372036854775807ulong: 0 : 18446744073709551615float: -3,402823E+38 : 3,402823E+38double: -1,79769313486232E+308 : 1,79769313486232E+308decimal: -79228162514264337593543950335 : 79228162514264337593543950335
Exercise 2.3. Exploring the type Char
The type System.Char (a struct) contains a number of useful
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. Hexadecimal numbers
In this exercise we will write a program that can convert between 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 typesSlide Annotated slide Contents IndexReferences Textbook
Enumeration types provide for symbolic names of selected integer values. Use of enumeration types improves the readability of your programs.
Enumeration types are similar to each other in C and C#
Program: Two examples of enumeration types in C#.
public enum Ranking {Bad, OK, Good}
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.Enumo 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 of enumeration types in C#. Programming with Ranking and OnOff.
using System;
class NonSimpleTypeDemo{
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 program that demonstrates enumeration types.
Status is OnRanking is OKRanking is GoodRanking is 33 defined: FalseGood defined: True2 defined: TrueBad
OKGood
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 Enumeration types
Consult the documentation of type type System.Enum, and get a 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 typesSlide Annotated slide Contents IndexReferences Textbook
This is about arrays, strings, structs. All the classes and structs that we program ourselves also count as non-simple types.
C# allows for a variety of non-simple types, most important Classes
Similaritieso Arrays in C#: Indexed from 0. Jagged arrays -
arrays of arrayso Strings in C#: Same notation as in C, and similar
escape characters
o Structs in C#: A value type like in C.
Differenceso 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 StringsSlide Annotated slide Contents IndexReferences Textbook
Both arrays and strings are classical types, supported by almost any programming language. Both arrays and strings are 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
Differenceso Arrays in C# can be rectangular or jagged (arrays
of arrays)o In C#, an array is not a pointer to the first elemento 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 demonstration program.
Array lengths. a1:3 b2:8 c1:2Lenght of a2: 10Sorting a1:abbccc
Program: A demonstration of strings in C#.
using System;
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 string demonstration program.
s1 and s2: OOP OOP
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 types
Based on the inspiration from the accompanying example, you 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 types
Based on the inspiration from the accompanying example, you 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 referencesSlide Annotated slide Contents IndexReferences Textbook
References are important in C#. A reference is similar to a point in C, but references are much easier to work with. References can be passed around (via parameters). Objects are 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
Pointerso 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 of references in C#.
using System;
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 reference demo program.
Is cRef null: TrueIs cRef null: Falsex 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
StructsSlide Annotated slide Contents IndexReferences Textbook
Structs in C and C# are similar to each other. But structs in C# are extended in several ways compared to C.
The concept of structs has been much extended in C#
Similaritieso Structs in C# can be used almost in the same way
as structs in Co Structs are value types in both C and C#
Differenceso 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 of structs in C#.
using System;
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 struct demo program.
Point is: (-3,-4)
Program: An extended demonstration of structs in C#.
/* Right, Wrong */
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); }
}
OperatorsSlide Annotated slide Contents IndexReferences Textbook
This pages shows an overview of all operators in C#.
Most operators in C are also found in C#
Table. The operator priority table of C#. Operators with high level numbers have high priorities. In a given expression, operators of high priority are evaluated before operators with lower priority. The associativity tells if operators at the same level are evaluated from left to right or from right to left.
Level Category Operators Associativity (binary/tertiary)
14 Primary x.y f(x) a[x] x++ x-- new typeof checked unchecked default delegate
left to right
13 Unary + - ! ~ ++x --x (T)x true false sizeof
left to right
12 Multiplicative * / % left to right
11 Additive + - left to right
10 Shift << >> left to right
9 Relational and Type testing
< <= > >= is as
left to right
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 Lambda expression
= *= /= %= += -= <<= >>= &= ^= |= =>
right to left
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 StructuresSlide Annotated slide Contents IndexReferences Textbook
iteration. As usual, we concentrate on the differences between C an C#.
Almost all control structures in C can be used the same way in C#
Similaritieso 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
Differenceso The C# foreach loop provides for easy traversal
of all elements in a collectiono 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 of definite assignment.
using System;
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 of if.
/* Right, Wrong */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 of switch.
/* Right, Wrong */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 of foreach.
/* Right, Wrong */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 of try catch.
/* Right, Wrong */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");
} } }
FunctionsSlide Annotated slide Contents IndexReferences Textbook
On this page we will look at parameter passing techniques. C only supports call by value. Call by reference in C is in reality 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#
Differenceso 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 parameterso 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 simple functions in C#.
/* Right, Wrong */
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 parameter passing in C#.
using System;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 overloaded methods in C#.
using System;
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 outputSlide Annotated slide Contents IndexReferences Textbook
Input and output (IO) is handled by a number of different classes in C#. In both C and C# there very few traces of IO in 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
Differenceso There is no direct counterpart to C's scanf in C#
o Comprehensive formatting support of DateTime objects in C#
Program: Demonstrations of Console output in C#.
/* Right, Wrong */
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 output demo program.
Argument number only: 1 1,1Formatting codes d and f: 3 3,30Field width: 4 4,40Left aligned: 5 5,50 Precision: 00006 6,60000
Exponential: 7,00000e+000 7,70000e+000Currency: kr 8,00 kr 8,89General: 9 9,9Hexadecimal: 0000cDateTime formatting with F: 4. juli 2008 15:35:31DateTime formatting with G: 04-07-2008 15:35:31DateTime formatting with T: 15:35:31
Program: Demonstrations of Console input in C#.
/* Right, Wrong */
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 with the Console IO demo program. Input is shown in bold style. Boldface items represent the input entered by the user of the program.
Input a single character: a Character read: aInput an integer: 123 Integer read: 123Input a double: 456,789 Double read: 456,79
References System.String.Format
System.Console
System.Int32
System.Double
CommentsSlide Annotated slide Contents IndexReferences 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 JavaSlide Annotated slide Contents IndexReferences Textbook
With respect to the basic language constructs, C# and Java are very close to each other
Typeso 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
TypesSlide Annotated slide Contents IndexReferences Textbook
Similarities.o Classes in both C# and Javao Interfaces in both C# and Java
Differences.o Structs in C#, not in Javao Delegates in C#, not in Javao Nullable types in C#, not in Java
o Class-like Enumeration types in Java; Simpler approach in C#
OperationsSlide Annotated slide Contents IndexReferences Textbook
Similarities: Operations in both Java and C#o Methods
Differences: Operations only in C#o Propertieso Indexerso Overloaded operators
o Anonymous methods
Other substantial differencesSlide Annotated slide Contents IndexReferences Textbook
Program organizationo No requirements to source file organization in C#
Exceptionso No catch or specify requirement in C#
Nested and local classeso 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 IndexReferences Textbook
Program: Typical overall program structure of a Visual Basic Program.
Module MyModule
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 program structure of a C# Program.
using System;
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 PictureSlide Annotated slide Contents IndexReferences Textbook
Program organizationo 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
Commentso VB: From an apostrophe to the end of the lineo C#: From // to the end of the line or /* ... */
Case sensitivenesso 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 IndexReferences Textbook
Program: A Visual Basic Program with a number of variable declarations.
Option Strict OnOption Explicit On
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# program with a number of variable declarations.
using System;
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 TypesSlide Annotated slide Contents IndexReferences Textbook
Declaration structureo VB: Variable before typeo C#: Variable after type
Types provide by the languageso The same underlying types
o Known under slightly different names in VB and C#
VB and C# share the .NET types
Expressions and OperatorsSlide Annotated slide Contents IndexReferences Textbook
Program: A Visual Basic Program with expressions and operators.
Option Strict OnOption Explicit On
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# program with a number of expressions and operators.
using System;class ExpressionsDemo{
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 Program with expressions and operators.
Option Strict OnOption Explicit On
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# program with a number of expressions and operators.
using System;class ExpressionsDemo{
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 Program with expressions and operators.
Option Strict OnOption Explicit On
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 SubEnd Module
Program: The similar C# program with a number of expressions and operators.
using System;class ExpressionsDemo{
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 OperatorsSlide Annotated slide Contents IndexReferences Textbook
Operator Precedence
o Major differences between the two languages
References Operator precedence
in C#
VB operator precedence
Equality and Assignmento 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 SelectionSlide Annotated slide Contents IndexReferences Textbook
Program: A Visual Basic Program with an If Then Else control structure.
Module IfDemo
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# program with an if else control structure.
using System;
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 Program with a Select control structure.
Module IfDemo
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 SubEnd Module
Program: The similar C# program with a switch control structure.
using System;
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 SelectionSlide Annotated slide Contents IndexReferences Textbook
If-then-elseo 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 IterationSlide Annotated slide Contents IndexReferences Textbook
Program: A Visual Basic Program with a while loop.
Module WhileDemo
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 SubEnd Module
Program: The similar C# program with a while loop.
using System;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 Program with a for loop.
Module ForDemo
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 SubEnd Module
Program: The similar C# program with a for loop.
using System;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 Program with a Do Loop.
Option Strict OnOption Explicit OnModule 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 SubEnd Module
Program: The similar C# program with a similar for and a break.
using System;class ForDemo{
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 IndexReferences Textbook
Whileo Very similar in C# and VBo C#: Does also support a do ... while
Do Loopo VB: Elegant, powerful, and symmetric.o No direct counterpart in C#
Foro C#: The for loop is very powerful.
o VB: Similar to classical for loop from Algol and Pascal
ArraysSlide Annotated slide Contents IndexReferences Textbook
Program: A Visual Basic Program with an array of 10 elements.
Option Strict OnOption Explicit OnModule 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 SubEnd Module
Program: The similar C# program with an array of 10 elements.
using System;
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]); }}
ArraysSlide Annotated slide Contents IndexReferences Textbook
Notationo VB: a(i)o C#: a[i]
Rangeo Both from zero to an upper limito 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 FunctionsSlide Annotated slide Contents IndexReferences Textbook
Program: A Visual Basic Program with a procedure - Subprogram.
Option Strict OnOption Explicit OnModule 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# program with void method.
using System;class ProcedureDemo{
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 Program with a function.
Option Strict OnOption Explicit OnModule 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# program with int method.
using System;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 FunctionsSlide Annotated slide Contents IndexReferences Textbook
Procedureso VB: Subprogramo C#: void method (void function)
Functionso VB: Functionso C#: int method or someType method
Parameter passing
o Both languages support call by value and call by reference
Combined C# and Visual Basic ProgrammingSlide Annotated slide Contents IndexReferences
A client written in Visual Basic and a server written in C#
Program: A class Die programmed in C#.
using System;
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 Die programmed in Visual Basic.
Imports System
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 execution.
csc /t:library die.csvbc /r:die.dll client.vb
client
Object-oriented programming in Visual BasicSlide Annotated slide Contents IndexReferences Textbook
Both VB and C# supports object-oriented programming on the .Net platform
C# Tools and IDEs
C# Tools on WindowsSlide Annotated slide Contents IndexReferences Textbook
Microsoft supplies several different set of tools that support the C# programmer
.NET Framework SDK 3.5o "Software Development Kit"o Command line tools, such as the C# compiler csc
Visual C# Expresso 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 UnixSlide Annotated slide Contents IndexReferences Textbook
The MONO project provides tools for C# development on Linux, Solaris, Mac OS X, Windows, and Unix.
MONOo An open source project (sponsored by Novell)o Corresponds the the Microsoft SDKo Based on ECMA specifications of C# and the
Common Language Infrastructure (CLI) Virtual Machine
o Command line toolso Compilers: mcs (C# 1.5) and gmcs (C# 2.0)
MONO on cs.aau.dko 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 ToolsSlide Annotated slide Contents IndexReferences Textbook
It is important to have access to documentation of the C# standard class library
Local documentationo The SDK 3.5 comes with a special documentation
browsero Visual C# Express has integrated documentation
available Documentation from a Microsoft webserver
o Link from the course home page - C# resources
Collected referencesContents Index
Computer Language HistoryThe struct System.DecimalThe struct System.DoubleThe struct System.SingleThe struct System.UInt64
The struct System.Int64The struct System.UInt32The struct System.Int32The struct System.UInt16The struct System.Int16The struct System.ByteThe struct System.SbyteDecimal Floating Point in .NETThe struct System.CharSystem.EnumSystem.StringSystem.ArraySimilar table for CSystem.DoubleSystem.Int32System.ConsoleSystem.String.FormatVB operator precedenceOperator precedence in C#C# Express Video Lectures
Recommended