C# The New Language For.NET

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

9 A Preview of.net 2.0

9 A Preview of.net 2.0 473 9 A Preview of.net 2.0 Microsoft.NET is an evolving system that is continuously improved and extended. In late 2003 Microsoft announced.net 2.0 (codename Whidbey) as a major new version of.net; a beta

More information

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

3. Basic Concepts. 3.1 Application Startup

3. Basic Concepts. 3.1 Application Startup 3.1 Application Startup An assembly that has an entry point is called an application. When an application runs, a new application domain is created. Several different instantiations of an application may

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

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduce C# as Object Oriented programming language. Explain, tokens, Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation

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

Object-Oriented Programming in C# (VS 2012)

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

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 Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

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

Game Engineering: 2D

Game Engineering: 2D Game Engineering: 2D CS420-2010F-02 Intro to CSharp David Galles Department of Computer Science University of San Francisco 02-0: C++ v. Java We will be coding in C# for this class Java is very similar

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

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

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

PES INSTITUTE OF TECHNOLOGY

PES INSTITUTE OF TECHNOLOGY Seventh Semester B.E. IA Test-I, 2014 USN 1 P E I S PES INSTITUTE OF TECHNOLOGY C# solution set for T1 Answer any 5 of the Following Questions 1) What is.net? With a neat diagram explain the important

More information

NOIDATUT E Leaning Platform

NOIDATUT E Leaning Platform NOIDATUT E Leaning Platform Dot Net Framework Lab Manual COMPUTER SCIENCE AND ENGINEERING Presented by: NOIDATUT Email : e-learn@noidatut.com www.noidatut.com C SHARP 1. Program to display Hello World

More information

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017 C++\CLI Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017 Comparison of Object Models Standard C++ Object Model All objects share a rich memory model: Static, stack, and heap Rich object life-time

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

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify

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

Introduction to.net, C#, and Visual Studio. Part I. Administrivia. Administrivia. Course Structure. Final Project. Part II. What is.net?

Introduction to.net, C#, and Visual Studio. Part I. Administrivia. Administrivia. Course Structure. Final Project. Part II. What is.net? Introduction to.net, C#, and Visual Studio C# Programming Part I Administrivia January 8 Administrivia Course Structure When: Wednesdays 10 11am (and a few Mondays as needed) Where: Moore 100B This lab

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

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

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

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

This tutorial has been prepared for the beginners to help them understand basics of c# Programming. About thetutorial C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft within its.net initiative led by Anders Hejlsberg. This tutorial covers basic C# programming

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

Object-oriented Programming. Object-oriented Programming

Object-oriented Programming. Object-oriented Programming 2014-06-13 Object-oriented Programming Object-oriented Programming 2014-06-13 Object-oriented Programming 1 Object-oriented Languages object-based: language that supports objects class-based: language

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations , 1 C#.Net VT 2009 Course Contents C# 6 hp approx. BizTalk 1,5 hp approx. No exam, but laborations Course contents Architecture Visual Studio Syntax Classes Forms Class Libraries Inheritance Other C# essentials

More information

inside: THE MAGAZINE OF USENIX & SAGE August 2003 volume 28 number 4 PROGRAMMING McCluskey: Working with C# Classes

inside: THE MAGAZINE OF USENIX & SAGE August 2003 volume 28 number 4 PROGRAMMING McCluskey: Working with C# Classes THE MAGAZINE OF USENIX & SAGE August 2003 volume 28 number 4 inside: PROGRAMMING McCluskey: Working with C# Classes & The Advanced Computing Systems Association & The System Administrators Guild working

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh C# Fundamentals Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2018/19 H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19

More information

Language Specification

Language Specification # Language Specification File: C# Language Specification.doc Last saved: 5/7/2001 Version 0.28 Copyright? Microsoft Corporation 1999-2000. All Rights Reserved. Please send corrections, comments, and other

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

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

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

Self-review Questions

Self-review Questions 7Class Relationships 106 Chapter 7: Class Relationships Self-review Questions 7.1 How is association between classes implemented? An association between two classes is realized as a link between instance

More information

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio Introduction XXV Part I: C# Fundamentals 1 Chapter 1: The.NET Framework 3 What s the.net Framework? 3 Common Language Runtime 3.NET Framework Class Library 4 Assemblies and the Microsoft Intermediate Language

More information

Computing is about Data Processing (or "number crunching") Object Oriented Programming is about Cooperating Objects

Computing is about Data Processing (or number crunching) Object Oriented Programming is about Cooperating Objects Computing is about Data Processing (or "number crunching") Object Oriented Programming is about Cooperating Objects C# is fully object-oriented: Everything is an Object: Simple Types, User-Defined Types,

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

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

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts ISBN 0-321-49362-1 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

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

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309 A Arithmetic operation floating-point arithmetic, 11 12 integer numbers, 9 11 Arrays, 97 copying, 59 60 creation, 48 elements, 48 empty arrays and vectors, 57 58 executable program, 49 expressions, 48

More information

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

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

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

Whidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004

Whidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004 Whidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004 Outline Practical Partial types Static classes Extern and the namespace alias qualifier Cool (and practical too) Generics Nullable Types

More information

DAD Lab. 1 Introduc7on to C#

DAD Lab. 1 Introduc7on to C# DAD 2017-18 Lab. 1 Introduc7on to C# Summary 1..NET Framework Architecture 2. C# Language Syntax C# vs. Java vs C++ 3. IDE: MS Visual Studio Tools Console and WinForm Applica7ons 1..NET Framework Introduc7on

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

Course Hours

Course Hours Programming the.net Framework 4.0/4.5 with C# 5.0 Course 70240 40 Hours Microsoft's.NET Framework presents developers with unprecedented opportunities. From 'geoscalable' web applications to desktop and

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

CPSC 3740 Programming Languages University of Lethbridge. Data Types

CPSC 3740 Programming Languages University of Lethbridge. Data Types Data Types A data type defines a collection of data values and a set of predefined operations on those values Some languages allow user to define additional types Useful for error detection through type

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

September 10,

September 10, September 10, 2013 1 Bjarne Stroustrup, AT&T Bell Labs, early 80s cfront original C++ to C translator Difficult to debug Potentially inefficient Many native compilers exist today C++ is mostly upward compatible

More information

IC Language Specification

IC Language Specification CS 301 Spring 2016 IC Language Specification The IC Language For the implementation project, you will build a compiler for an object-oriented language called IC (for Irish Coffee 1 ), which is essentially

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments CMSC433, Spring 2004 Programming Language Technology and Paradigms Java Review Jeff Foster Feburary 3, 2004 Administrivia Reading: Liskov, ch 4, optional Eckel, ch 8, 9 Project 1 posted Part 2 was revised

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

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

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

In this chapter, we will delve into types and type members.

In this chapter, we will delve into types and type members. 3 Creating Types in C# In this chapter, we will delve into types and type members. Classes A class is the most common kind of reference type. The simplest possible class declaration is as follows: class

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

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

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

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

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.5: Methods A Deeper Look Xianrong (Shawn) Zheng Spring 2017 1 Outline static Methods, static Variables, and Class Math Methods with Multiple

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

SWE344. Internet Protocols and Client-Server Programming

SWE344. Internet Protocols and Client-Server Programming SWE344 Internet Protocols and Client-Server Programming Module 1a: 1a: Introduction Dr. El-Sayed El-Alfy Mr. Bashir M. Ghandi alfy@kfupm.edu.sa bmghandi@ccse.kfupm.edu.sa Computer Science Department King

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

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

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

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code

More information

Applied object oriented programming. 4 th lecture

Applied object oriented programming. 4 th lecture Applied object oriented programming 4 th lecture Today Constructors in depth Class inheritance Interfaces Standard.NET interfaces IComparable IComparer IEquatable IEnumerable ICloneable (and cloning) Kahoot

More information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

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

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

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

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

Prerequisites: The student should have programming experience in a high-level language. ITCourseware, LLC Page 1. Object-Oriented Programming in C#

Prerequisites: The student should have programming experience in a high-level language. ITCourseware, LLC Page 1. Object-Oriented Programming in C# Microsoft s.net is a revolutionary advance in programming technology that greatly simplifies application development and is a good match for the emerging paradigm of Web-based services, as opposed to proprietary

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# and Java. C# and Java are both modern object-oriented languages

C# and Java. C# and Java are both modern object-oriented languages C# and Java C# and Java are both modern object-oriented languages C# came after Java and so it is more advanced in some ways C# has more functional characteristics (e.g., anonymous functions, closure,

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

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

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer. The Compiler So Far CSC 4181 Compiler Construction Scanner - Lexical analysis Detects inputs with illegal tokens e.g.: main 5 (); Parser - Syntactic analysis Detects inputs with ill-formed parse trees

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

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened

More information

Implementing Subprograms

Implementing Subprograms Implementing Subprograms 1 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables Nested Subprograms Blocks Implementing

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

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

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 3a Andrew Tolmach Portland State University 1994-2017 Binding, Scope, Storage Part of being a high-level language is letting the programmer name things: variables

More information