Sunteți pe pagina 1din 28

Advanced Programming Concepts Objectoriented C#

Prof. Dr. Stefan Eicker, Peter M. Schuler Winter Semester 2005 Version 2.0

Chair of Business Informatics and Software Engineering Prof. Dr. Stefan Eicker

Object Terminology
a program
consists of

simple
are grouped in contain

e.g.

int class or struct

types
have

are

structured

e.g.

namespaces
and

data member
are

function member
are have

methods fields
are

parameters

events

constructors finalizers properties indexers operators


Based on: [BiHo2004, p. 31]

constants variables

Properties
Methods that are dressed to look like a field get accessor takes no parameter and returns the same type as the property has been declared as No specification of explicit parameters for the set accesor Implement Read- and Write-Only Property by omitting the compliment property Note: C# does not permit to setting different access modifiers Properties can be declared as virtual or abstract
public string SomeProperty { get { return This is the Property value, } set { // code to set the property } }
Source: [Robi2002, p. 117-119]

Constructors
Compiler will supply a default constructor, if explicitly no other constructor is implemented If you supply any constructor that takes parameters, then the compiler will not automatically supply a default one Constructors can be defined as private or protected It is possibly in C# to write a static no-parameter constructor for a class (no access modifiers)
public class MyClass { public MyClass () {} }

Source: [Robi2002, p. 130-140]

Readonly Fields
Keyword readonly You can assign values to a readonly field inside a constructor A readonly field can be an instance rather than a static field.

public class Document


{ public readonly DateTime CreationDate; public Document() { // read in creation date from file. Assume result // is 1 Jan 2002 but in general this can be // different for different instances of the class CreationDate = new DateTime(2002, 1, 1); } }
Source: [Robi2002, p. 146-148]

Structs

Are value types, not reference types Do not support inheritance Compiler always supplies default constructor with no parameters, which cant be replaced You can often treat them in the same way as classes
struct Dimension { public double Length; public double Width; }

Source: [Robi2002, p. 148]

Structs (2)

new operator works different for structs Calls the appropriate constructor, according to the parameters passed to it, and initializes all fields Legal to write:
Dimensions point; point.Length = 3; point.Width = 6;

Everything must be initialized before use either with


the new operator or when values have been assigned to all of its fields but a struct can not derive from any other class and you can not inherit from as struct

Structs derive from System.Object


-

You are not permitted to define a constructor that takes no parameters It is not permitted to define a destructor
Source: [Robi2002, p. 148-151]

The Object Class

Method
string ToString() int GetHashTable() bool Equals (object obj) bool Equals (object objA, object objB) bool ReferenceEquals (object objA, object objB) Type GetType() object MemberwiseClone() void Finalize()

Access Modifiers
public virtual public virtual public virtual public static public static

Purpose
Returns a string representation of the object. Used if implementing dictionaries (hash tables). Compares instances of the object for equality. Compares instances of the object for equality. Compares whether two references refer to the same object. Returns details of the type of the object. Makes a shallow copy of the object. This is the .NET version of a destructor.

public protected protected virtual

Source: [Robi2002, p. 120]

Access Modifiers

Accessibility public internal protected

Description
The variable or method can be accessed from anywhere as a field of the type to which it belongs. The variable or method can only be accessed from the same assembly. The variable or method can only be accessed from within the type to which it belongs, or from types derived from that type. The variable or method can be accessed from the current assembly, or from types derived from the current type (that is, from anywhere that could access it if it were declared as protected or internal). The variable or method can only be accessed from within the type to which it belongs.
Source: [Robi2002, p. 116]

protected internal

private

Interfaces
Interfaces act as contracts A class, which derives from an interface, is declaring that it implements certain functions Not permitted to supply implementations of any of the members of an interface Interfaces can only obtain declarations of methods, properties, indexers and events Interface members are always public and cannot be declared as virtual or static
public interface Idisposable { void Dispose(); }
Source: [Robi2002, p. 122-123]

10

Constructor Initializer
Special syntax in C# which allows to place code of different constructors in one place class Car { private string description; private uint nWheels; public Car (string model, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car (string model) : this(model, 4) { } }
Source: [Robi2002, p. 134]

11

Constructors (2)

Constructors are called in Order of System.Object Then progressed down the hierarchy until it has reached the class being instantiated Each constructor handles initializations of the fields in his own class Working up the hierarchy a constructor for the derived class can call up base class methods, properties and any other members The base and this keywords are the only keyword allowed in the line which calls another constructor

Source: [Robi2002, p. 130-140]

12

Call Order for Constructors

System.Object

MyType

Wert

Public Mat() { Wert = 0; }


Source: [Robi2002, p. 439.]

MyAdvType

13

Classes and Inheritance

Classes are reference types


class MyClass { private int someField; public string SomeMethod(bool parameters){} }

Instantiate an object using the new operator


MyClass my Object; myObject = new MyClass();

Source: [Robi2002, p. 110]

14

Single Implementation Inheritance

A class must derive from one another class Universal base class derives from System.Object A class may derive from another specific class
class MyDerivedClass : MyBaseClass { }

Source: [Robi2002, p. 110-111]

15

Method Overloading

Methods may be implemented in several versions Requirement: signatures differ at least in one the following
- Name - Number of parameters - Parameter types

Signatures that differ only


- In their return type - By virtue of parameter (ref or out)

are not sufficient!


void DisplayResult (string result){} void DisplayResult (int result){}

Source: [Robi2002, p. 111-112]

16

Method Overriding

A base class must be declared is virtual in order to be overridden Neither member fields nor static functions can be declared as virtual
public override string VirtualMethod() {}

Source: [Robi2002, p. 112]

17

Method Hiding
A method is declared in both base and derived classes and not declared as virtual and override derived class version hides the base class version
class MyDerivedClass : HisBaseClass { public int MyMethod() {} }

Use the keyword new to declare that you intend to hide a method
public new int MyMethod() {}

To call a base version of a method from a derived class


base.CalculatePrice();
Source: [Robi2002, p. 112-114]

18

Abstract Classes and Methods

An abstract class can not be instantiated An abstract function does not have an implementation Abstract function must be overridden in any non-abstract derived class
abstract class Building { public abstract decimal CalculateHeatingCost(); }

Source: [Robi2002, p. 115]

19

Sealed Classes and Methods

You can not inherit from a sealed class You can not override a sealed method any further

sealed class FinalClass { public sealed void FinalMethod() {} }

Source: [Robi2002, p. 115-116]

20

Advanced Programming Concepts Objectoriented C#


Prof. Dr. Stefan Eicker, Peter M. Schuler Winter Semester 2005 Version 2.0

Chair of Business Informatics and Software Engineering Prof. Dr. Stefan Eicker

21

Agenda

Operator Overloading Type Casts Indexer

22

Operator Overloading

Operators like +, - or * are strictly implemented for the predefined data types If you want to use the operators for your own classes, you have to use overloads for the operators
public static Vector operator + (Vector lhs, Vector rhs) { Vector result = new Vector(lhs); result.x += rhs.x; result.y += rhs.y; result.z += rhs.z; return result; }

Source: [Robi2002, p. 151-161]

23

Which Operators Can You Overload?

Category
Arithmetic binary Arithmetic unary Bitwise binary Bitwise unary Comparison

Operators
+, *, /, -, % +, -, ++, -&, |, ^, <<, >> !, ~, true, false ==, !=, >=, <, <=, >

Restrictions
none none none none must be overloaded in pairs

Source: [Robi2002, p. 161]

24

Indexers

Are not an essential part of object-oriented programming. Name of the indexer is the keyword this, other then that it is quite equal to properties in terms of their definition.

Source: [Robi2002, p. 162-165]

25

Indexers (2)
struct Vector { public double x, y, z; public double this [int i] { get { switch (i) { case 0: return x; case 1: return y; case 2: return z; default: throw new IndexOutOfRangeException("Attempt to retrieve Vector element " + i) ; } }
Source: [Robi2002, p. 162-163]

26

Indexers (3)
set { switch (i) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; default: throw new IndexOutOfRangeException( "Attempt to set Vector element " + i); } } }
Source: [Robi2002, p. 162-163]

27

Comparision of Property and Indexer

Property
Identified by its name. Accessed through a simple name or a member access. Can be a static or an instance member. A get accessor of a property has no parameters. A set accessor of a property contains the implicit value parameter.

Indexer
Identified by its signature. Accessed through an element access. Must be an instance member. A get accessor of an indexer has the same formal parameter list as the indexer. A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.

Quelle: [MSDN2003]
28

S-ar putea să vă placă și