C# The New Language For.NET

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "C# The New Language For.NET"

Transcription

1 secure: [si-'kyur] 1: free from danger 2: free from risk of loss 3: affording safety C# The New Language For.NET Andreas Schabus Academic Relations Microsoft Österreich GmbH Based on Slides by Prof. Dr. H. Mössenböck University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

2 Features of C# Very similar to Java 70% Java, 10% C++, 5% Visual Basic, 15% neu As in Java Object-orientation (single inheritance) Interfaces Generics (more powerful than in Java) Exceptions Threads Namespaces (similar to Java packages) Strong typing Garbage collection Reflection Dynamic loading of code... As in C++ Operator overloading Pointer arithmetic in unsafe code Some syntactic details

3 New Features in C# Really new (compared to Java) Call-by-reference parameters Stack-allocated objects (structs) Block matrices Enumerations Uniform type system goto statement Attributes System-level programming Versioning "Syntactic Sugar" Component-based programming - Properties - Events Delegates Indexers foreach loop Boxing / unboxing...

4 Hello World Program File Hello.cs using System; class Hello { static void Main() { Console.WriteLine("Hello World"); imports the namespace System entry point must be called Main prints to the console file name and class name need not be identical. Compilation (from the Console window; produces Hello.exe) csc Hello.cs Execution Hello

5 Structure of C# Programs Programm File1.cs File2.cs File3.cs namespace A {... namespace B {... namespace C {... class X {... class Y {... class Z {... If no namespace is specified => anonymous default namespace Namespaces may also contain structs, interfaces, delegates and enums Namespace may be "reopened" in other files Simplest case: single class, single file, default namespace

6 A Program Consisting of 2 Files Counter.cs class Counter { int val = 0; public void Add (int x) { val = val + x; public int Val () { return val; Prog.cs using System; class Prog { static void Main() { Counter c = new Counter(); c.add(3); c.add(5); Console.WriteLine("val = " + c.val()); Compilation csc /target:exe Counter.cs Prog.cs Execution Prog Working with DLLs csc /t:library Counter.cs => generates Counter.dll csc /r:counter.dll Prog.cs => generates Prog.exe

7 SYMBOLS

8 Identifiers Syntax Identifier = (letter '_' {letter digit '_'. Unicode! Case-sensitive can be used to treat keywords as identifiers - if... keyword identifier if May contain Unicode escape sequences (e.g. \u03c0 for p) Examples somename sum_of3 p \u03c0 b\u0061ck the identifier while the identifier p the identifier p the identifier back

9 Naming Conventions Casing Words are capitalized (z.b. ShowDialog) First letter in upper case, except for private or local variables, constants and fields constants upper case SIZE, MAX_VALUE local variables lower case i, top, sum private fields lower case data, lastelement public fields upper case Width, BufferLength properties upper case Length, FullName enumeration constants upper case Red, Blue methods upper case Add, IndexOf types upper case StringBuilder (predefined types in lower case: int, string) namespaces upper case System, Collections First word Names of void methods should start with a verb (e.g. GetHashCode) Other names should start with a noun (e.g. size, IndexOf, Collections) Enumeration constants or bool members may start with an adjective (Red, Empty)

10 Comments Single-line comments // a comment Delimited comments /* a comment */ must not be nested Documentation comments /// a documentation comment

11 TYPES University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

12 Uniform Type System Types Value Types Reference Types Pointers Simple Types Enums Structs Classes Interfaces Arrays Delegates bool char sbyte short int long byte ushort uint ulong float double decimal User-defined Types blue types are missing from Java All types are compatible with object - can be assigned to variables of type object - all operations of type object are applicable to them

13 Value Types and Reference Types Value Types Reference Types variable contains value reference stored on stack heap initialisation 0, false, '\0' null assignment copies the value copies the reference example int i = 17; string s = "Hello"; int j = i; string s1 = s; i 17 s H e l l o j 17 s1

14 Primitive Types long form in Java range sbyte System.SByte byte byte System.Byte short System.Int16 short ushort System.UInt int System.Int32 int uint System.UInt long System.Int64 long ulong System.UInt float System.Single float 1.5E E38 (32 Bit) double System.Double double 5E E308 (64 Bit) decimal System.Decimal --- 1E E28 (128 Bit) bool System.Boolean boolean true, false char System.Char char Unicode character

15 Compatibility Between Primitive Types decimal double float long int short sbyte only with type cast ulong uint ushort byte char The following assignments are legal intvar = shortvar; intvar = charvar; floatvar = charvar; decimalvar = (decimal)doublevar;

16 Arrays One-dimensional arrays int[] a = new int[3]; int[] b = new int[] {3, 4, 5; int[] c = {3, 4, 5; SomeClass[] d = new SomeClass[10]; SomeStruct[] e = new SomeStruct[10]; // array of references // array of values (directly in the array) Multidimensional arrays (jagged) int[][] a = new int[2][]; a[0] = new int[] {1, 2, 3; a[1] = new int[] {4, 5, 6; // array of references to other arrays // cannot be initialized directly Multidimensional arrays (rectangular) int[,] a = new int[2, 3]; int[,] b = {{1, 2, 3, {4, 5, 6; int[,,] c = new int[2, 4, 2]; // block matrix // can be initialized directly

17 Class System.String Can be used as the standard type string string s = "Alfonso"; Note Strings are immutable (use StringBuilder if you want to modify strings) Can be concatenated with +: "Don " + s Can be indexed: s[i] String length: s.length Strings are reference types => reference semantics in assignments but their values can be compared with == and!= : if (s == "Alfonso")... Class String defines many useful operations: CompareTo, IndexOf, StartsWith, Substring,...

18 Variable-length Arrays using System; using System.Collections; class Test { static void Main() { ArrayList a = new ArrayList(); a.add("charly"); a.add("delta"); a.add("alpha"); a.sort(); for (int i = 0; i < a.count; i++) Console.WriteLine(a[i]); Output Alpha Charly Delta

19 Associative Arrays using System; using System.Collections; class Test { static void Main() { Hashtable phone = new Hashtable(); phone["karin"] = 7131; phone["peter"] = 7130; phone["wolfgang"] = 7132; foreach (DictionaryEntry x in phone) Console.WriteLine("{0 = {1", x.key, x.value); Output Karin = 7131 Peter = 7130 Wolfgang = 7132

20 Structs Declaration struct Point { public int x, y; public Point (int x, int y) { this.x = x; this.y = y; public void MoveTo (int a, int b) { x = a; y = b; // fields // constructor // methods Usage Point p; Point p = new Point(3, 4); p.x = 1; p.y = 2; p.moveto(10, 20); Point q = p; // still unititialized // constructor initializes object on the stack // field access // method call // value assignment of objects (all fields are assigned) Note Structs are value types! A struct declaration allocates an object directly on the stack or within some other object. Structs must not declare a parameterless constructor (they have one by default). However, they may use it: p = new Point(); // initializes fields to 0, null, false,...

21 Classes Declaration Usage Note class Rectangle { Point origin; public int width, height; public Rectangle() { origin = new Point(0,0); width = height = 0; public Rectangle (Point p, int w, int h) { origin = p; width = w; height = h; public void MoveTo (Point p) { origin = p; Rectangle r = new Rectangle(new Point(10, 20), 5, 5); int area = r.width * r.height; r.moveto(new Point(3, 3)); Rectangle r1 = r ; // reference assignment Classes are reference types; Their objects are allocated on the heap. The "new" operator allocates and object and calls its constructor. Classes may declare a parameterless constructor.

22 Differences Between Classes and Structs Classes Reference types (objects are allocated on the heap) support inheritance (all classes are derived from object) can implement interfaces may declare a parameter less constructor may have a destructor Structs Value types (objects are allocated on the stack) no inheritance (but they are compatible with object) can implement interfaces must not declare a parameter less constructor no destructors

23 DECLARATIONS University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

24 Declaration Space The program area to which a declaration belongs Kinds of declaration spaces - namespace: declarations of classes, interfaces, structs, enums, delegates - class, interface, struct: declaraions of fields, methods,... - enumeration: declarations of enumeration constants - block: declarations of local variables namespace N {... class C {... void Foo() {... if (...) {... Statement blocks are not declaration spaces on their own but belong to the declaration space of the enclosing method block

25 Using Other Namespaces Foreign namespaces must either be imported (e.g. using Util;) or specified in a qualified name (e.g. Util.Color) Most programs need the namespace System => using System; Color.cs Figures.cs Triangle.cs namespace Util { public enum Color {... using Util.Figures; namespace Util.Figures { public class Rect {... public class Circle {... namespace Util.Figures { public class Triangle {... class Test { Rect r; // without qualification (because of using Util.Figures) Triangle t; Util.Color c; // with qualification

26 CLASSES AND STRUCTS University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

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

28 Classes class Stack { int[] values; int top = 0; public Stack(int size) {... public void Push (int x) {... public int Pop() {... Objects are allocated on the heap (classes are reference types) Objects must be created with new Stack s = new Stack(100); Classes can inherit from one other class (single code inheritance) Classes can implement multiple interfaces (multiple type inheritance)

29 Structs struct Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; public MoveTo (int x, int y) {... Objects are allocated on the stack not on the heap (structs are value types) + efficient, low memory consumption, no burden for the garbage collector. - live only as long as their container (not suitable for dynamic data structures) Can be allocated with new Point p; // fields of p are not yet initialized Point q = new Point(); Fields must not be initialized at their declaration struct Point { int x = 0; // compilation error Parameter less constructors cannot be declared Can neither inherit nor be inherited, but can implement interfaces

30 Visibility Modifiers (excerpt) public private visible where the declaring namespace is known - Members of interfaces and enumerations are public by default. - Types in a namespace (classes, structs, interfaces, enums, delegates) have default visibility internal (visible in the declaring assembly) only visible in declaring class or struct - Members of classes and structs are private by default (fields, methods, properties,..., nested types) Example public class Stack { private int[] val; // private is also default private int top; // private is also default public Stack() {... public void Push(int x) {... public int Pop() {...

31 Fields and Constants class C { int value = 0; Field - initialization is optional - initialization value must be computable at compile time - fields of a struct must not be initialized const long size = ((long)int.maxvalue + 1) / 4; Constant - must be initialized - value must be computable at compile time readonly DateTime date; Read-only field - must be initialized in their declaration or in a constructor - value needs not be computable at compile time - value must not be changed later - consumes a memory location (like a field) Access within C Access from other classes... value... size... date... C c = new C();... c.value... c.size... c.date...

32 Static Fields and Constants Belong to a class, not to an object class Rectangle { static Color defaultcolor; // once per class static readonly int scale; // -- " -- int x, y, width,height; // once per object... Access within the class Access from other classes... defaultcolor... scale Rectangle.defaultColor... Rectangle.scale... Constants must not be declared static

33 Static Methods Operations on class data (static fields) class Rectangle { static Color defaultcolor; public static void ResetColor() { defaultcolor = Color.white; Access from Rectangle ResetColor(); Access from other classes Rectangle.ResetColor();

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

35 Variable Number of Parameters Last n parameters may be a sequence of values of a certain type. keyword params array type Usage void Add (out int sum, params int[] val) { sum = 0; foreach (int i in val) sum = sum + i; params cannot be used for ref and out parameters Add(out sum, 3, 5, 2, 9); // sum == 19 Another example void Console.WriteLine (string format, params object[] arg) {...

36 Method Overloading Methods of a class may have the same name - if they have different numbers of parameters, or - if they have different parameter types, or - if they have different parameter kinds (value, ref/out) Examples void F (int x) {... void F (char x) {... void F (int x, long y) {... void F (long x, int y) {... void F (ref int x) {... Calls int i; long n; short s; F(i); // F(int x) F('a'); // F(char x) F(i, n); // F(int x, long y) F(n, s); // F(long x, int y); F(i, s); // ambiguous between F(int x, long y) and F(long x, int y); => compilation error F(i, i); // ambiguous between F(int x, long y) and F(long x, int y); => compilation error Overloaded methods must not differ only in their function types, in the presence of params or in ref versus out!

37 Constructors for Classes Example class Rectangle { int x, y, width, height; public Rectangle (int x, int y, int w, int h) {this.x = x; this.y = y; width = x; height = h; public Rectangle (int w, int h) : this(0, 0, w, h) { public Rectangle () : this(0, 0, 0, 0) {... Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(2, 5); Rectangle r3 = new Rectangle(2, 2, 10, 5); Constructors can be overloaded. A constructor may call another constructor with this (specified in the constructor head, not in its body as in Java!). Before a constructor is called, fields are possibly initialized.

38 Default Constructor If no constructor was declared in a class, the compiler generates a parameterless default constructor : class C { int x; C c = new C(); // ok default constructor initializes all fields as follows: numeric 0 enumeration 0 bool false char '\0' reference null If a constructor was declared, no default constructor is generated : class C { int x; public C(int y) { x = y; C c1 = new C(); // compilation error C c2 = new C(3); // ok

39 Constructor for Structs Example struct Complex { double re, im; public Complex(double re, double im) { this.re = re; this.im = im; public Complex(double re) : this(re, 0) {... Complex c0; // c0.re and c0.im uninitialized Complex c1 = new Complex(); // c1.re == 0, c1.im == 0 Complex c2 = new Complex(5); // c2.re == 5, c2.im == 0 Complex c3 = new Complex(10, 3); // c3.re == 10, c3.im == 3 For every struct the compiler generates a parameterless default constructor (even if there are other constructors). The default constructor zeroes all fields. Programmers must not declare a parameterless constructor for structs (for implementation reasons of the CLR). A constructor of a struct must initialize all fields.

40 Static Constructors Both for classes and for structs class Rectangle {... static Rectangle() { Console.WriteLine("Rectangle initialized"); struct Point {... static Point() { Console.WriteLine("Point initialized"); Must be parameterless (also for structs) and have no public or private modifier. There must be just one static constructor per class/struct. Is invoked once before this type is used for the first time. Used for initialization of static fields.

41 Destructors class Test { ~Test() {... cleanup actions... Correspond to finalizers in Java. Called for an object before it is removed by the garbage collector. Can be used, for example, to close open files. Base class destructor is called automatically at the end. No public or private. Is dangerous (object resurrection) and should be avoided Structs must not have a destructor (reason unknown).

42 Properties Syntactic sugar for get/set methods class Data { FileStream s; property type property name public string FileName { set { s = new FileStream(value, FileMode.Create); get { return s.name; "input parameter" of the set method Used as "smart fields" Data d = new Data(); d.filename = "myfile.txt"; string s = d.filename; // calls set("myfile.txt") // calls get() JIT compilers often inline get/set methods no efficiency penalty.

43 Properties (continued) Assignment operators work also on properties class C { private static int size; public static int Size { get { return size; set { size = value; C.Size = 3; C.Size += 2; // Size = Size + 2;

44 Properties (continued) get or set can be omitted class Account { long balance; public long Balance { get { return balance; x = account.balance; account.balance =...; // ok // illegal Why are properties a good idea? Allow read-only and write-only fields. Can validate a field when it is accessed. Interface and implementation of data can differ. Substitute for fields in interfaces.

45 Indexers Programmable operator for indexing a collection class File { FileStream s; Usage public int this [int index] { get { s.seek(index, SeekOrigin.Begin); return s.readbyte(); set { s.seek(index, SeekOrigin.Begin); s.writebyte((byte)value); File f =...; int x = f[10]; f[10] = 'A'; type of the indexed expression // calls f.get(10) // calls f.set(10, 'A') name (always this) type and name of the index value get or set method can be omitted (write-only / read-only) indexers can be overloaded with different index type.net library has indexers for string (s[i]), ArrayList (a[i]), etc.

46 Conversion Operators Implicit conversion - If the conversion is always possible without loss of precision - e.g. long = int; Explicit conversion - If a run time check is necessary or truncation is possible - e.g. int = (int) long; Conversion operators for user-defined types Usage class Fraction { int x, y;... public static implicit operator Fraction (int x) { return new Fraction(x, 1); public static explicit operator int (Fraction f) { return f.x / f.y; Fraction f = 3; // implicit conversion, f.x == 3, f.y == 1 int i = (int) f; // explicit conversion, i == 3

47 Nested Types class A { private int x; B b; public void Foo() { b.bar();... public class B { A a; public void Bar() { a.x =...;... a.foo();... class C { A a = new A(); A.B b = new A.B(); For auxiliary classes that should be hidden - Inner class can access all members of the outer class (even private members). - Outer class can access only public members of the inner class. - Other classes can access an inner class only if it is public. Nested types can also be structs, enums, interfaces and delegates.

48 INHERITANCE University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

49 Syntax class A { int a; public A() {... public void F() {... // base class class B : A { // subclass (inherits from A, extends A) int b; public B() {... public void G() {... B inherits a and F(), it adds b and G() - constructors are not inherited - inherited methods can be overridden (see later) Single inheritance: a class can only inherit from one base class, but it can implement multiple interfaces. A class can only inherit from a class, not from a struct. Structs cannot inherit from another type, but they can implement multiple interfaces. A class without explicit base class inherits from object.

50 Assignments and Type Checks class A {... class B : A {... class C: B {... Assignments A a = new A(); // static type of a: the type specified in the declaration (here A) // dynamic type of a: the type of the object in a (here also A) a = new B(); // dynamic type of a is B a = new C(); // dynamic type of a is C B b = a; // forbidden; compilation error Run-time type checks a = new C(); if (a is C)... // true, if the dynamic type of a is C or a subclass; otherwise false if (a is B)... // true if (a is A)... // true, but warning because it makes no sense a = null; if (a is C)... // false: if a == null, a is T always returns false

51 Checked Type Casts Cast A a = new C(); B b = (B) a; C c = (C) a; a = null; c = (C) a; // if (a is B) stat.type(a) is B in this expression; else exception // ok null can be casted to any reference type as A a = new C(); B b = a as B; C c = a as C; a = null; c = a as C; // if (a is B) b = (B)a; else b = null; // c == null

52 Overriding Methods Only methods that are declared as virtual can be overridden in subclasses class A { public void F() {... // cannot be overridden public virtual void G() {... // can be overridden in a subclass Overriding methods must be declared as override class B : A { public void F() {... // warning: hides inherited F() use new public void G() {... // warning: hides inherited G() use new public override void G() { // ok: overrides inherited G... base.g(); // calls inherited G() Method signatures must be identical - same number and types of parameters (including function type) - same visibility (public, protected,...). Properties and indexers can also be overridden (virtual, override). Static methods cannot be overridden.

53 Hiding Members can be declared as new in a subclass. They hide inherited members with the same name and signature. class A { public int x; public void F() {... public virtual void G() {... class B : A { public new int x; public new void F() {... public new void G() {... B b = new B(); b.x =...; b.f();... b.g(); ((A)b).x =...; ((A)b).F();... ((A)b).G(); // accesses B.x // calls B.F and B.G // accesses A.x! // calls A.F and A.G!

54 Visibility protected and internal Protected Visible in the declaring class and its subclasses (more restricive than in Java) Visible in the declaring assembly (see later) internal protected internal Visible in declaring class, its subclasses and the declaring assembly Example class Stack { protected int[] values = new int[32]; protected int top = -1; public void Push(int x) {... public int Pop() {... class BetterStack : Stack { public bool Contains(int x) { foreach (int y in values) if (x == y) return true; return false; class Client { Stack s = new Stack();... s.values[0]... // illegal: compilation error

55 Abstract Classes Example abstract class Stream { public abstract void Write(char ch); public void WriteString(string s) { foreach (char ch in s) Write(s); class File : Stream { public override void Write(char ch) {... write ch to disk... Note Abstract methods do not have an implementation. Abstract methods are implicitly virtual. If a class has abstract methods (declared or inherited) it must be abstract itself. One cannot create objects of an abstract class..

56 Abstract Properties and Indexers Example abstract class Sequence { public abstract void Add(object x); public abstract string Name { get; public abstract object this [int i] { get; set; // method // property // indexer class List : Sequence { public override void Add(object x) {... public override string Name { get {... public override object this [int i] { get {... set {... Note Overridden indexers and properties must have the same get and set methods as in the base class

57 Example sealed class Account : Asset { long val; public void Deposit (long x) {... public void Withdraw (long x) { Note sealed classes cannot be extended (same as final classes in Java), but they can inherit from other classes. override methods can be declared as sealed individually. Reason: Security (avoids inadvertent modification of the class semantics) Efficiency (methods can possibly be called using static binding)

58 Class System.Object Topmost base class of all other classes class Object { protected object MemberwiseClone() {... public Type GetType() {... public virtual bool Equals (object o) {... public virtual string ToString() {... public virtual int GetHashCode() {... Directly usable: Type t = x.gettype(); object copy = x.memberwiseclone(); is protected!) returns a type descriptor (for reflection) does a shallow copy (this method Overridable in subclasses: x.equals(y) x.tostring() int code = x.gethashcode(); should compare the values of x and y should return a string representation of x should return a hash code for x

59 Example (for using object) class Fraction { int x, y; public Fraction(int x, int y) { this.x = x; this.y = y;... public override string ToString() { return String.Format("{0/{1", x, y); public override bool Equals(object o) { Fraction f = (Fraction)o; return f.x == x && f.y == y; public override int GetHashCode() { return x ^ y; public Fraction ShallowCopy() { return (Fraction) MemberwiseClone(); class Client { static void Main() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(1, 2); Fraction c = new Fraction(3, 4); Console.WriteLine(a.ToString()); // 1/2 Console.WriteLine(a); // 1/2 (ToString is called automatically) Console.WriteLine(a.Equals(b)); Console.WriteLine(a == b); Console.WriteLine(a.GetHashCode()); // 3 // true // false a = c.shallowcopy(); Console.WriteLine(a); // 3/4

60 Example (for overloading == and!=) class Fraction { int x, y; public Fraction(int x, int y) { this.x = x; this.y = y;... public static bool operator == (Fraction a, Fraction b) { return a.x == b.x && a.y == b.y; public static bool operator!= (Fraction a, Fraction b) { return! (a == b); class Client { static void Main() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(1, 2); Fraction c = new Fraction(3, 4); Console.WriteLine(a == b); // true Console.WriteLine((object)a == (object)b); // false Console.WriteLine(a.Equals(b)); // true, because overridden in Fraction If == is overloaded,!= must be overloaded as well. Compiler prints a warning if == and!= are overloaded, but Equals is not overridden.

61 New Features in C# 2.0 Generic Types Iterators Simplified Delegates Anonymous Methods Partial Types Various University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License

62 GENERIC TYPES

63 Problems Without Generic Types Assume we need a class that can work with arbitrary objects class Buffer { private object[] data; public void Put(object x) {... public object Get() {... Problems Type casts needed buffer.put(3); int x = (int)buffer.get(); // boxing imposes run-time costs // type cast imposes run-time costs One cannot statically enforce homogeneous data structures buffer.put(3); buffer.put(new Rectangle()); Rectangle r = (Rectangle)buffer.Get(); // can result in a run-time error! Special types IntBuffer, RectangleBuffer,... introduce redundancy

64 Generic Class Buffer generic type placeholder type class Buffer<Element> { private Element[] data; public Buffer(int size) {... public void Put(Element x) {... public Element Get() {... works also for structs and interfaces placeholder type Element can be used like a normal type Usage Buffer<int> a = new Buffer<int>(100); a.put(3); // accepts only int parameters; no boxing int i = a.get(); // no type cast needed! Buffer<Rectangle> b = new Buffer<Rectangle>(100); b.put(new Rectangle()); // accepts only Rectangle parameters Rectangle r = b.get(); // no typ cast needed! Benefits homogeneous data structure with compile-time type checking efficient (no boxing, no type casts) Genericity is also available in Ada, Eiffel, C++ (templates), Java 1.5

65 Multiple Placeholder Types Buffer with priorities class Buffer <Element, Priority> { private Element[] data; private Priority[] prio; public void Put(Element x, Priority prio) {... public void Get(out Element x, out Priority prio) {... Usage Buffer<int, int> a = new Buffer<int, int>(); a.put(100, 0); int elem, prio; a.get(out elem, out prio); Buffer<Rectangle, double> b = new Buffer<Rectangle, double>(); b.put(new Rectangle(), 0.5); Rectangle r; double prio; b.get(out r, out prio); C++ allows also placeholders for constants, C# does not

66 Constraints Constraints about placeholder types are specified as base types class OrderedBuffer <Element, Priority> where Priority: IComparable { Element[] data; Priority[] prio; int lastelem;... public void Put(Element x, Priority p) { int i = lastelement; while (i >= 0 && p.compareto(prio[i]) > 0) {data[i+1] = data[i]; prio[i+1] = prio[i]; i--; data[i+1] = x; prio[i+1] = p; Allows operations on instances of placeholder types interface or base class Usage OrderedBuffer<int, int> a = new OrderedBuffer<int, int>(); a.put(100, 3); parameter must implement IComparable

67 Multiple Constraints class OrderedBuffer <Element, Priority> where Element: MyClass where Priority: IComparable where Priority: ISerializable {... public void Put(Element x, Priority p) {... public void Get(out Element x, out Priority p) {... Usage must be a subclass of MyClass must implement IComparable and ISerializable OrderedBuffer<MySubclass, MyPrio> a = new OrderedBuffer<MySubclass, MyPrio>();... a.put(new MySubclass(), new MyPrio(100));

68 Constructor Constraint For creating objects of a generic types class Stack<T, E> where E: Exception, new() { T[] data =...; int top = -1; public void Push(T x) { if (top >= data.length) throw new E(); else data[++top] = x; specifies that the placeholder E must have a parameterless constructor. Usage class MyException: Exception { public MyException(): base("stack overflow or underflow") { Stack<int, MyException> stack = new Stack<int, MyException>();... stack.push(3);

69 Genericity and Inheritance class Buffer <Element>: List<Element> {... public void Put(Element x) { this.add(x); // Add is inherited from List can also implement generic interfaces From which classes may a generic class be derived? from a non-generic class class T<X>: B {... from an instantiated generic class class T<X>: B<int> {... from a generic class class T<X>: B<X> {... with the same placeholder

70 Methoden that can work with arbitrary data types Generic Methods static void Sort<T> (T[] a) where T: IComparable { for (int i = 0; i < a.length-1; i++) { for (int j = i+1; j < a.length; j++) { if (a[j].compareto(a[i]) < 0) { T x = a[i]; a[i] = a[j]; a[j] = x; can sort any array as long as the array elements implement IComparable Usage int[] a = {3, 7, 2, 5, 3;... Sort<int>(a); // a == {2, 3, 3, 5, 7 string[] s = {"one", "two", "three";... Sort<string>(s); // s == {"one", "three", "two" From the method parameters the compiler can usually infer the concrete type that is to be substituted for the placeholder type; so one can simply write: Sort(a); // a == {2, 3, 3, 5, 7 Sort(s); // s == {"one", "three", "two"

71 Null Values Setting a value to null void Foo<T>() { T x = null; T y = 0; T z = T.default; // error // error // ok! 0, '\0', false, null Comparing a value against null void Foo<T>(T x) { if (x == null) { Console.WriteLine(true); else { Console.WriteLine(false"); for reference types x == null does a comparison for value types x == null returns false Foo(3); Foo(0); Foo("Hello"); Foo<string>(null); // false // false // false // true

72 Namespace System.Collections.Generic New generic types Classes List<T> Dictionary<T, U> SortedDictionary<T, U> Stack<T> Queue<T> corresponds to ArrayList corresponds to Hashtable There is no SortedList<T> However, List<T> can be sorted with the Sort method Interfaces ICollection<T> IList<T> IDictionary<T, U> IEnumerable<T> IEnumerator<T> IComparable<T> IComparer<T>

73 ITERATORS

74 Iterators so far foreach loop can be applied to objects of classes which implement IEnumerable class MyClass: IEnumerable {... public IEnumerator GetEnumerator() { return new MyEnumerator(...); interface IEnumerable { IEnumerator GetEnumerator(); class MyEnumerator: IEnumerator { public object Current { get {... public bool MoveNext() {... public void Reset() {... MyClass x = new MyClass();... foreach (object obj in x)... complicated to implement!!

75 Iterator Methods class MyClass { string first = "first"; string second = "second"; string third = "third";... public IEnumerator GetEnumerator() { yield return first; yield return second; yield return third; Characteristics of an interator method 1. has the signature public IEnumerator GetEnumerator 2. statement body contains at least one yield statement MyClass x = new MyClass();... foreach (string s in x) Console.Write(s + " "); // liefert "first second third" How does an iterator method work? 1. returns a sequence of values 2. foreach loop traverses this sequence Note MyClass need not implement IEnumerable! Instead of IEnumerator it is better to use IEnumerator<string> (avoids a type cast) IEnumerator<T> is in System.Collections.Generic

76 What Happens Behind the Scene? returns an object of the following class public IEnumerator<int> GetEnumerator() { try {... finally {... class _Enumerator : IEnumerator<int> { int Current { get {... bool MoveNext() {... void Dispose() {... is translated into foreach (int x in list) Console.WriteLine(x); IEnumerator<int> _e = list.getenumerator(); try { while (_e.movenext()) Console.WriteLine(_e.Current); finally { if (_e!= null) _e.dispose(); MoveNext runs to the next yield statement Dispose executes a possibly existing finally block in the iterator method

77 yield Statement 2 kinds yield return expr; yields a value for the foreach loop may only occur in an iterator method type of expr must be compatible with - T (if IEnumerator<T>) - object (otherwise) yield break; terminates the iteration may only occur in an iterator method

78 Example: Iterating Over a Tree class Tree { Node root = null; public void Add(int val) {... public bool Contains(int val) {... public IEnumerator<int> GetEnumerator() { return root.getenumerator(); class Node { public int val; public Node left, right; public Node(int x) { val = x; Usage... Tree tree = new Tree();... foreach (int x in tree) Console.WriteLine(x); public IEnumerator<int> GetEnumerator() { if (left!= null) foreach (int x in left) yield return x; yield return val; if (right!= null) foreach (int x in right) yield return x; Creates an enumerator object for every node of the tree!

79 ANONYMOUS METHODS

80 Ordinary Delegates delegate void Visitor(Node p); class List { Node[] data =...;... public void ForAll(Visitor visit) { for (int i = 0; i < data.length; i++) visit(data[i]); class C { int sum = 0; void SumUp(Node p) { sum += p.value; void Print(Node p) { Console.WriteLine(p.value); void Foo() { List list = new List(); list.forall(sumup); list.forall(print); requires the declaration of a named method (SumUp, Print,...) SumUp and Print cannot access the local variables of Foo => sum must be declared as a global field

81 Anonymous Methods delegate void Visitor(Node p); class C { void Foo() { List list = new List(); int sum = 0; list.forall(delegate (Node p) { Console.WriteLine(p.value); ); list.forall(delegate (Node p) { sum += p.value; ); formal parameter code class List {... public void ForAll(Visitor visit) {... method code is specified in-place does not require the declaration of a named method anonymous method can access Foo's local variable sum return terminates the anonymous method (not the enclosing method) Restrictions anonymous methods must not have formal parameters of the kind params T[] anonymous methods must not be assigned to object anonymous methods must not access ref or out parameters of the enclosing method

82 Further Simplification delegate void EventHandler (object sender, EventArgs arg); Button button = new Button(); Button.Click += delegate (object sender, EventArgs arg) { Console.WriteLine("clicked"); ; Can be simplified as follows Button.Click += delegate { Console.WriteLine("clicked"); ; Formal parameters can be omitted if they are not used in the method body Restriction Formal parameters can only be omitted if the delegate type does not have out parameters

83 PARTIAL TYPES

84 Class Consisting of Multiple Parts public partial class C { int x; public void M1(...) {... public int M2(...) {... public partial class C { string y; public void M3(...) {... public void M4(...) {... public void M5(...) {... file Part1.cs file Part2.cs Benefit Parts can be grouped by functionality different developers can work on different parts of the class at the same time one part can be machine-generated, other parts can be hand-written Should only be used as an exception

85 VARIOUS

86 Static Classes May only have static fields and methods static class Math { public static double Sin(double x) {... public static double Cos(double x) { Benefit shows explicitly that this class contains only static members the compiler can make sure that all members are declared as static Static classes must not be used as types

87 The Evolution of C# C# 2.0 C# 3.0 Generics Local variable type inference, Lambda expressions, Object instantiation, Anonymous types, Extension methods C# 1.0 Components on a Managed Runtime

88 Work Citied Mössenböck, H., Beer, W., Prähofer, H., & Wöß, A. ( ). Application Development with C# and.net. Retrieved March 06, 2008, from

89

Distribution and Integration Technologies. C# Language

Distribution and Integration Technologies. C# Language Distribution and Integration Technologies C# Language Classes Structs Interfaces Delegates Enums C# Java C C++ C# C++.NET A C# program is a collection of: (can be grouped in namespaces) One entry point

More information

C# Java. C# Types Naming Conventions. Distribution and Integration Technologies. C# C++.NET A C# program is a collection of: C C++ C# Language

C# Java. C# Types Naming Conventions. Distribution and Integration Technologies. C# C++.NET A C# program is a collection of: C C++ C# Language C# Java Distribution and Integration Technologies C# Language C C++ C# C++.NET A C# program is a collection of: Classes Structs Interfaces Delegates Enums (can be grouped in namespaces) One entry point

More information

Object-Oriented Programming in C# (VS 2015)

Object-Oriented Programming in C# (VS 2015) Object-Oriented Programming in C# (VS 2015) This thorough and comprehensive 5-day course is a practical introduction to programming in C#, utilizing the services provided by.net. This course emphasizes

More information

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. 1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity

More information

C#: framework overview and in-the-small features

C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

DigiPen Institute of Technology

DigiPen Institute of Technology DigiPen Institute of Technology Presents Session Two: Overview of C# Programming DigiPen Institute of Technology 5001 150th Ave NE, Redmond, WA 98052 Phone: (425) 558-0299 www.digipen.edu 2005 DigiPen

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

C# Programming in the.net Framework

C# Programming in the.net Framework 50150B - Version: 2.1 04 May 2018 C# Programming in the.net Framework C# Programming in the.net Framework 50150B - Version: 2.1 6 days Course Description: This six-day instructor-led course provides students

More information

Table of Contents Preface Bare Necessities... 17

Table of Contents Preface Bare Necessities... 17 Table of Contents Preface... 13 What this book is about?... 13 Who is this book for?... 14 What to read next?... 14 Personages... 14 Style conventions... 15 More information... 15 Bare Necessities... 17

More information

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo Learning C# 3.0 Jesse Liberty and Brian MacDonald O'REILLY Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo Table of Contents Preface xv 1. C# and.net Programming 1 Installing C# Express 2 C# 3.0

More information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Namespaces Classes Fields Properties Methods Attributes Events Interfaces (contracts) Methods Properties Events Control Statements if, else, while, for, switch foreach Additional Features Operation Overloading

More information

C# machine model. Programming Language Concepts and Implementation Fall 2011, Lecture 2. Rasmus Ejlers Møgelberg

C# machine model. Programming Language Concepts and Implementation Fall 2011, Lecture 2. Rasmus Ejlers Møgelberg C# machine model Programming Language Concepts and Implementation Fall 2011, Lecture 2 Reference types vs. value types Structs 2-dimensional arrays Overview Method calls: call-by-value vs. call-by-reference

More information

Introduction To C#.NET

Introduction To C#.NET Introduction To C#.NET Microsoft.Net was formerly known as Next Generation Windows Services(NGWS).It is a completely new platform for developing the next generation of windows/web applications. However

More information

Industrial Programming

Industrial Programming Industrial Programming Lecture 3: C# Fundamentals Industrial Programming 1 C# Types Industrial Programming 2 Value Types Memory location contains the data. Integers: Signed: sbyte, int, short, long Unsigned:

More information

Multiple Choice: 2 pts each CS-3020 Exam #3 (CH16-CH21) FORM: EX03:P

Multiple Choice: 2 pts each CS-3020 Exam #3 (CH16-CH21) FORM: EX03:P Multiple Choice: 2 pts each CS-3020 Exam #3 (CH16-CH21) FORM: EX03:P Choose the BEST answer of those given and enter your choice on the Answer Sheet. You may choose multiple options, but the point value

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 12 Thomas Wies New York University Review Last lecture Modules Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic

More information

C# Language Specification

C# Language Specification Standard ECMA- December 00 Standardizing Information and Communication Systems C# Language Specification. Phone: +.0.00 - Fax: +.0.0 - URL: http://www.ecma.ch - Internet: helpdesk@ecma.ch Brief history

More information

Visual Studio.NET.NET Framework. Web Services Web Forms Windows Forms. Data and XML classes. Framework Base Classes. Common Language Runtime

Visual Studio.NET.NET Framework. Web Services Web Forms Windows Forms. Data and XML classes. Framework Base Classes. Common Language Runtime Intro C# Intro C# 1 Microsoft's.NET platform and Framework.NET Enterprise Servers Visual Studio.NET.NET Framework.NET Building Block Services Operating system on servers, desktop, and devices Web Services

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objects self-contained working units encapsulate data and operations exist independantly of each other (functionally, they may depend) cooperate and communicate to perform a

More information

C # Language Specification

C # Language Specification C # Language Specification Copyright Microsoft Corporation 1999-2001. All Rights Reserved. Please send corrections, comments, and other feedback to sharp@microsoft.com Notice 1999-2001 Microsoft Corporation.

More information

C# Language Reference

C# Language Reference C# Language Reference Owners: Anders Hejlsberg and Scott Wiltamuth File: clangref Last saved: 6/26/2000 Last printed: 7/10/2000 Version 0.17b Copyright Microsoft Corporation 1999-2000. All Rights Reserved.

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages 1 / 26 CSE 307: Principles of Programming Languages Names, Scopes, and Bindings R. Sekar 2 / 26 Topics Bindings 1. Bindings Bindings: Names and Attributes Names are a fundamental abstraction in languages

More information

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types Chapter 6 Topics WEEK E FOUR Data Types Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference

More information

Arrays, Strings and Collections

Arrays, Strings and Collections Arrays Arrays can be informally defined as a group of variables containing values of the same type and that in some way or another they are related. An array has a fixed size that is defined before the

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 2 Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2011 PLC 2011, Lecture 2, 6 January 2011 Classes and

More information

Framework Fundamentals

Framework Fundamentals Questions Framework Fundamentals 1. Which of the following are value types? (Choose all that apply.) A. Decimal B. String C. System.Drawing.Point D. Integer 2. Which is the correct declaration for a nullable

More information

C# s A Doddle. Steve Love. ACCU April 2013

C# s A Doddle. Steve Love. ACCU April 2013 C# s A Doddle Steve Love ACCU April 2013 A run through C# (pronounced See Sharp ) is a simple, modern, object-oriented, and type-safe programming language. C# has its roots in the C family of languages,

More information

Microsoft Visual C# Step by Step. John Sharp

Microsoft Visual C# Step by Step. John Sharp Microsoft Visual C# 2013 Step by Step John Sharp Introduction xix PART I INTRODUCING MICROSOFT VISUAL C# AND MICROSOFT VISUAL STUDIO 2013 Chapter 1 Welcome to C# 3 Beginning programming with the Visual

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

C # Version 2.0 Specification

C # Version 2.0 Specification C # Version 2.0 Specification July 2003 Copyright Microsoft Corporation 1999-2003. All Rights Reserved. Notice 2003 Microsoft Corporation. All rights reserved. Microsoft, Windows, Visual Basic, Visual

More information

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can

More information

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2 CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

DC69 C# and.net JUN 2015

DC69 C# and.net JUN 2015 Solutions Q.2 a. What are the benefits of.net strategy advanced by Microsoft? (6) Microsoft has advanced the.net strategy in order to provide a number of benefits to developers and users. Some of the major

More information

Values and Variables 1 / 30

Values and Variables 1 / 30 Values and Variables 1 / 30 Values 2 / 30 Computing Computing is any purposeful activity that marries the representation of some dynamic domain with the representation of some dynamic machine that provides

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data Declaring Variables Constant Cannot be changed after a program is compiled Variable A named location in computer memory that can hold different values at different points in time

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

C and C++ 7. Exceptions Templates. Alan Mycroft

C and C++ 7. Exceptions Templates. Alan Mycroft C and C++ 7. Exceptions Templates Alan Mycroft University of Cambridge (heavily based on previous years notes thanks to Alastair Beresford and Andrew Moore) Michaelmas Term 2013 2014 1 / 20 Exceptions

More information

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

Microsoft. Microsoft Visual C# Step by Step. John Sharp

Microsoft. Microsoft Visual C# Step by Step. John Sharp Microsoft Microsoft Visual C#- 2010 Step by Step John Sharp Table of Contents Acknowledgments Introduction xvii xix Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 1 Welcome to

More information

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking CS 430 Spring 2015 Mike Lam, Professor Data Types and Type Checking Type Systems Type system Rules about valid types, type compatibility, and how data values can be used Benefits of a robust type system

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

Chapter 11. Abstract Data Types and Encapsulation Concepts

Chapter 11. Abstract Data Types and Encapsulation Concepts Chapter 11 Abstract Data Types and Encapsulation Concepts Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language Examples Parameterized

More information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

More information

Module 4: Data Types and Variables

Module 4: Data Types and Variables Module 4: Data Types and Variables Table of Contents Module Overview 4-1 Lesson 1: Introduction to Data Types 4-2 Lesson 2: Defining and Using Variables 4-10 Lab:Variables and Constants 4-26 Lesson 3:

More information

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

Client-Side Web Technologies. JavaScript Part I

Client-Side Web Technologies. JavaScript Part I Client-Side Web Technologies JavaScript Part I JavaScript First appeared in 1996 in Netscape Navigator Main purpose was to handle input validation that was currently being done server-side Now a powerful

More information

Industrial Programming

Industrial Programming Industrial Programming Lecture 4: C# Objects & Classes Industrial Programming 1 What is an Object Central to the object-oriented programming paradigm is the notion of an object. Objects are the nouns a

More information

C++ (classes) Hwansoo Han

C++ (classes) Hwansoo Han C++ (classes) Hwansoo Han Inheritance Relation among classes shape, rectangle, triangle, circle, shape rectangle triangle circle 2 Base Class: shape Members of a class Methods : rotate(), move(), Shape(),

More information

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

IST311. Advanced Issues in OOP: Inheritance and Polymorphism IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition

More information

IT 528 Developing.NET Applications Using C# Gülşen Demiröz

IT 528 Developing.NET Applications Using C# Gülşen Demiröz IT 528 Developing.NET Applications Using C# Gülşen Demiröz Summary of the Course Hands-on applications programming course We will learn how to develop applications using the C# programming language on

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

Course Syllabus C # Course Title. Who should attend? Course Description

Course Syllabus C # Course Title. Who should attend? Course Description Course Title C # Course Description C # is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the.net Framework.

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

C # 7, 8, and beyond: language features from design to release to IDE support. Kevin

C # 7, 8, and beyond: language features from design to release to IDE support. Kevin C # 7, 8, and beyond: language features from design to release to IDE support Kevin Pilch kevinpi@microsoft.com @Pilchie Stack Overflow - most popular technologies http://stackoverflow.com/insights/survey/2017#most-popular-technologies

More information

CMSC 4023 Chapter 11

CMSC 4023 Chapter 11 11. Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language Examples Parameterized Abstract Data Types Encapsulation Constructs Naming Encapsulations

More information

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored

More information

PIC 20A The Basics of Java

PIC 20A The Basics of Java PIC 20A The Basics of Java Ernest Ryu UCLA Mathematics Last edited: November 1, 2017 Outline Variables Control structures classes Compilation final and static modifiers Arrays Examples: String, Math, and

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Java: framework overview and in-the-small features

Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

EVALUATION COPY. Unauthorized reproduction or distribution is prohibitied C# ESSENTIALS

EVALUATION COPY. Unauthorized reproduction or distribution is prohibitied C# ESSENTIALS C# ESSENTIALS C# Essentials Rev. 4.8 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted.

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science Department Lecture 3: C# language basics Lecture Contents 2 C# basics Conditions Loops Methods Arrays Dr. Amal Khalifa, Spr 2015 3 Conditions and

More information

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

Introduction to C# Applications Pearson Education, Inc. All rights reserved. 1 3 Introduction to C# Applications 2 What s in a name? That which we call a rose by any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

Java and C# in Depth

Java and C# in Depth Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 4 Chair of Software Engineering Don t forget to form project groups by tomorrow (March

More information

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete. CMSC433, Fall 2001 Programming Language Technology and Paradigms Adam Porter Sept. 4, 2001 C++ without Classes Don t need to say struct New libraries function overloading confusing link messages default

More information

CMSC 331 Second Midterm Exam

CMSC 331 Second Midterm Exam 1 20/ 2 80/ 331 First Midterm Exam 11 November 2003 3 20/ 4 40/ 5 10/ CMSC 331 Second Midterm Exam 6 15/ 7 15/ Name: Student ID#: 200/ You will have seventy-five (75) minutes to complete this closed book

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

Module 6: Fundamentals of Object- Oriented Programming

Module 6: Fundamentals of Object- Oriented Programming Module 6: Fundamentals of Object- Oriented Programming Table of Contents Module Overview 6-1 Lesson 1: Introduction to Object-Oriented Programming 6-2 Lesson 2: Defining a Class 6-10 Lesson 3: Creating

More information

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis? Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator

More information

The Java Programming Language

The Java Programming Language The Java Programming Language Slide by John Mitchell (http://www.stanford.edu/class/cs242/slides/) Outline Language Overview History and design goals Classes and Inheritance Object features Encapsulation

More information

Basic Types, Variables, Literals, Constants

Basic Types, Variables, Literals, Constants Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic

More information

10/9/2012. Computers are machines that process data. assignment in C# Primitive Data Types. Creating and Running Your First C# Program

10/9/2012. Computers are machines that process data. assignment in C# Primitive Data Types. Creating and Running Your First C# Program Primitive Data Types 1. Creating and Running Your First C# Program Integer Floating-Point / Decimal Floating-Point Boolean Character String Object Declaring and Using Variables 2. Identifiers Declaring

More information

Procedure and Object- Oriented Abstraction

Procedure and Object- Oriented Abstraction Procedure and Object- Oriented Abstraction Scope and storage management cs5363 1 Procedure abstractions Procedures are fundamental programming abstractions They are used to support dynamically nested blocks

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Language Fundamentals Summary

Language Fundamentals Summary Language Fundamentals Summary Claudia Niederée, Joachim W. Schmidt Software Systems Institute Object-oriented Analysis and Design 1998/99 c.niederee@tu-harburg.de http://www.sts.tu-harburg.de Keywords

More information

Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition

Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition 11 Features Advanced Object-Oriented Programming C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 1 4th Edition Chapter Objectives Learn the

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Generics. Thomas J. Fuchs

Generics. Thomas J. Fuchs Generics Thomas J. Fuchs Parametric Polymorphism (Generics) Benefits: Code reuse Faster code (no runtime casts) Safer programming (static type-checking) World s first cross-language generics (not just

More information

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction 1. Which language is not a true object-oriented programming language? A. VB 6 B. VB.NET C. JAVA D. C++ 2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a)

More information