advanced c #

Click here to load reader

Upload: csilla

Post on 21-Feb-2016

32 views

Category:

Documents


0 download

DESCRIPTION

Advanced C #. Learning Objectives. Advanced features of the C# language Creating custom types with interfaces, classes and structs Delegates and events Miscellaneous topics. Agenda. Review Object-Oriented Concepts Interfaces Classes and Structs Delegates Events Attributes - PowerPoint PPT Presentation

TRANSCRIPT

Advanced C#

Advanced C#1

Learning ObjectivesAdvanced features of the C# languageCreating custom types with interfaces, classes and structsDelegates and eventsMiscellaneous topics

4This module is designed to update C++ and Java programmers with the fundamentals of C#.

AgendaReview Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code5Objects, instances and classesIdentityEvery instance has a unique identity, regardless of its dataEncapsulationData and function are packaged togetherInformation hidingAn object is an abstractionUser should NOT know implementation detailsReview Key Object-Oriented Concepts6The term object sometimes refers to an instance and sometimes to a class. Its meaning can usually be determined by context.

Review Key Object-Oriented ConceptsInterfacesA well-defined contractA set of function membersTypesAn object has a type, which specifies its interfaces and their implementationsA variable also can have a typeInheritanceTypes are arranged in a hierarchyBase/derived, superclass/subclassInterface vs. implementation inheritance7An interface is a well-defined set of methods (functions). Interfaces do not contain data members.Type is different from class. The type specifies the interfaces, the class specifies the implementation.Review Key Object-Oriented ConceptsPolymorphismThe ability to use an object without knowing its precise type

DependenciesFor reuse and to facilitate development, systems should be loosely coupledDependencies should be minimized8Polymorphism is achieved through:Inheritance: a base type can have multiple derived typesInterfaces: multiple types can implement a given interfaceLate binding: you can use any object, as long as it implements the methods you want to call. In C# you can use reflection to dynamically determine if an object implements a method, and then call it. Interfaces can also be used in a late-bound manner.

In order to handle multiple types without polymorphism you have to write conditional code (using if or switch statements) that tests the type of an instance and then runs the appropriate code. Such code is brittle and not easily extended.

Many Object-Oriented design concepts are motivated by minimizing dependencies. You want to be able to develop independent modules, so that making a change to one doesnt force you to have to go back and change others.AgendaReview Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code9InterfacesAn interface defines a contractAn interface is a typeIncludes methods, properties, indexers, eventsAny class or struct implementing an interface must support all parts of the contractInterfaces provide no implementationWhen a class or struct implements an interface it must provide the implementationInterfaces provide polymorphismMany classes and structs may implement a particular interface10In scenarios where completely different objects need to support some kind of shared functionality like, lets say, persist to XML, classes can implement interfaces that make them compatible with even if they dont share the same base class. This provides most of the benefits of multiple class inheritance without the nasty side-effects that this usually brings.

Interface members are implicitly public and abstract.public interface IDelete { void Delete();}public class TextBox : IDelete { public void Delete() { ... }}public class Car : IDelete { public void Delete() { ... }}TextBox tb = new TextBox();IDelete iDel = tb;iDel.Delete();

Car c = new Car();iDel = c;iDel.Delete();InterfacesExample11interface IControl { void Paint();}interface IListBox: IControl { void SetItems(string[] items);}interface IComboBox: ITextBox, IListBox {}InterfacesMultiple InheritanceClasses and structs can inherit from multiple interfacesInterfaces can inherit from multiple interfaces

12interface IControl { void Delete();}interface IListBox: IControl { void Delete();}interface IComboBox: ITextBox, IListBox { void IControl.Delete(); void IListBox.Delete();}InterfacesExplicit Interface MembersIf two interfaces have the same method name, you can explicitly specify interface + method name to disambiguate their implementations13If theres no ambiguity then you do not have to specify the name of the interface.AgendaReview Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code14Classes and StructsSimilaritiesBoth are user-defined typesBoth can implement multiple interfacesBoth can containData Fields, constants, events, arraysFunctions Methods, properties, indexers, operators, constructorsType definitionsClasses, structs, enums, interfaces, delegates15Classes and structs provide a way to create user-defined types.ClassStructReference typeValue typeCan inherit from any non-sealed reference typeNo inheritance(inherits only from System.ValueType)Can have a destructorNo destructorCan have user-defined parameterless constructorNo user-defined parameterless constructorClasses and StructsDifferences16C++ StructC# StructSame as C++ class, but all members are publicUser-defined value typeCan be allocated on the heap, on the stack or as a member (can be used as value or reference)Always allocated on the stack or as a memberMembers are always publicMembers can be public, internal or privateClasses and StructsC# Structs vs. C++ StructsVery different from C++ struct17The C++ and C# structs are alike in name only.public class Car : Vehicle { public enum Make { GM, Honda, BMW } Make make; string vid; Point location; Car(Make m, string vid; Point loc) { this.make = m; this.vid = vid; this.location = loc; } public void Drive() { Console.WriteLine(vroom); }}Car c = new Car(Car.Make.BMW, JF3559QT98, new Point(3,7));c.Drive();Classes and StructsClass18public struct Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } }}Point p = new Point(2,5);p.X += 100;int px = p.X; // px = 102Classes and StructsStruct19Classes and StructsStatic vs. Instance MembersBy default, members are per instanceEach instance gets its own fieldsMethods apply to a specific instanceStatic members are per typeStatic methods cant access instance dataNo this variable in static methodsDont abuse static membersThey are essentially object-oriented global data and global functionsClasses and StructsAccess ModifiersAccess modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public, private, protected, internal, or protected internalStruct members can be public, private or internalIf the access modifier isThen a member defined in type T and assembly A is accessiblepublicto everyoneprivatewithin T only (the default)protectedto T or types derived from Tinternalto types within Aprotected internalto T or types derived from Tor to types within AClasses and StructsAccess Modifiers22protected internal = protected OR internal. No way to define protected AND internal.

Classes and StructsAbstract ClassesAn abstract class is one that cannot be instantiatedIntended to be used as a base classMay contain abstract and non-abstract function membersSimilar to an interfaceCannot be sealedClasses and StructsSealed ClassesA sealed class is one that cannot be used as a base classSealed classes cant be abstractAll structs are implicitly sealedWhy seal a class?To prevent unintended derivationCode optimizationVirtual function calls can be resolved at compile-time

class Person { string name; public Person(string name) { this.name = name; } public void Introduce(Person p) { if (p != this) Console.WriteLine(Hi, Im + name); }}Classes and StructsthisThe this keyword is a predefined variable available in non-static function members Used to access data and function members unambiguouslyclass Shape { int x, y; public override string ToString() { return "x=" + x + ",y=" + y; }}class Circle : Shape { int r; public override string ToString() { return base.ToString() + ",r=" + r; }}Classes and StructsbaseThe base keyword is used to access class members that are hidden by similarly named members of the current classpublic class MyClass { public const string version = 1.0.0; public const string s1 = abc + def; public const int i3 = 1 + 2; public const double PI_I3 = i3 * Math.PI; public const double s = Math.Sin(Math.PI); //ERROR ...}Classes and StructsConstantsA constant is a data member that is evaluated at compile-time and is implicitly static (per type)e.g. Math.PIClasses and StructsFieldsA field is a member variableHolds data for a class or structCan hold:a class instance (a reference), a struct instance (actual data), or an array of class or struct instances (an array is actually a reference)

Classes and StructsReadonly FieldsSimilar to a const, but is initialized at run-time in its declaration or in a constructorOnce initialized, it cannot be modifiedDiffers from a constant Initialized at run-time (vs. compile-time)Dont have to re-compile clientsCan be static or per-instancepublic class MyClass { public static readonly double d1 = Math.Sin(Math.PI); public readonly string s1; public MyClass(string s) { s1 = s; } }29Constants are compiled into client programs, while readonly fields are not.public class Button: Control { private string caption; public string Caption { get { return caption; } set { caption = value; Repaint(); } }}Button b = new Button();b.Caption = "OK";String s = b.Caption;Classes and StructsPropertiesA property is a virtual fieldLooks like a field, but is implemented with codeCan be read-only, write-only, or read/writepublic class ListBox: Control { private string[] items; public string this[int index] { get { return items[index]; } set { items[index] = value; Repaint(); } }}ListBox listBox = new ListBox();listBox[0] = "hello";Console.WriteLine(listBox[0]);Classes and StructsIndexersAn indexer lets an instance behave as a virtual arrayCan be overloaded (e.g. index by int and by string)Can be read-only, write-only, or read/writeClasses and StructsMethodsAll code executes in a methodConstructors, destructors and operators are special types of methodsProperties and indexers are implemented with get/set methodsMethods have argument listsMethods contain statementsMethods can return a valueOnly if return type is not void

Classes and StructsMethod Argument PassingBy default, data is passed by value

A copy of the data is created and passed to the method

void RefFunction(ref int p) { p++;}int x = 10;RefFunction(ref x);// x is now 11Classes and StructsMethod Argument PassingThe ref modifier causes arguments to be passed by referenceAllows a method call to modify a variableHave to use ref modifier in method definition and the code that calls itVariable has to have a value before call34Having to declare ref in the caller helps make the code more readable and maintainable.void OutFunction(out int p) { p = 22;}int x;OutFunction(out x);// x is now 22Classes and StructsMethod Argument PassingThe out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variableHave to use out modifier in method definition and the code that calls itArgument has to have a value before returningvoid Print(int i);void Print(string s);void Print(char c);void Print(float f);int Print(float f); // Error: duplicate signatureClasses and StructsOverloaded MethodsA type may overload methods, i.e. provide multiple methods with the same nameEach must have a unique signatureSignature is based upon arguments only, the return value is ignoredint Sum(params int[] intArr) { int sum = 0; foreach (int i in intArr) sum += i; return sum;}int sum = Sum(13,87,34);Classes and StructsParameter ArraysMethods can have a variable number of arguments, called a parameter arrayparams keyword declares parameter arrayMust be last argument37In the example, the Add function can be called with a variable number of arguments. Here, there are 3 arguments. Each is put into the intArr array. The function then iterates over the array, producing the sum of the 3 numbers.class Foo { public void DoSomething(int i) { ... }}Foo f = new Foo();f.DoSomething();Classes and StructsVirtual MethodsMethods may be virtual or non-virtual (default)Non-virtual methods are not polymorphicThey cannot be overriddenNon-virtual methods cannot be abstract

38When you call a non-virtual method M (DoSomething) on a class C (Foo), you are guaranteed that C.M (Foo.DoSomething) will be called.Classes and StructsVirtual MethodsDefined in a base classCan be overridden in derived classesDerived classes provide their own specialized implementationMay contain a default implementationUse abstract method if no default implementationA form of polymorphismProperties, indexers and events can also be virtualclass Shape { public virtual void Draw() { ... }}class Box : Shape { public override void Draw() { ... }}class Sphere : Shape { public override void Draw() { ... }}void HandleShape(Shape s) { s.Draw(); ...}HandleShape(new Box());HandleShape(new Sphere());HandleShape(new Shape());Classes and StructsVirtual MethodsClasses and StructsAbstract MethodsAn abstract method is virtual and has no implementationMust belong to an abstract classIntended to be implemented in a derived class

abstract class Shape { public abstract void Draw();}class Box : Shape { public override void Draw() { ... }}class Sphere : Shape { public override void Draw() { ... }}void HandleShape(Shape s) { s.Draw(); ...}HandleShape(new Box());HandleShape(new Sphere());HandleShape(new Shape()); // Error!Classes and StructsAbstract MethodsClasses and StructsMethod VersioningMust explicitly use override or new keywords to specify versioning intentAvoids accidental overridingMethods are non-virtual by default

class Derived: Base { // version 1 public virtual void Foo() { Console.WriteLine("Derived.Foo"); }}

class Base { // version 1}

Classes and StructsMethod Versioningclass Base { // version 2 public virtual void Foo() { Console.WriteLine("Base.Foo"); }}class Derived: Base { // version 2a new public virtual void Foo() { Console.WriteLine("Derived.Foo"); }}

class Derived: Base { // version 2b public override void Foo() { base.Foo(); Console.WriteLine("Derived.Foo"); }}44Lets say that we have a base class that doesnt do anything interesting.BUILD: Then a user of this class inherited this class and create a method named Foo()BUILD: Then the creator of the original base class realizes how Foo-ness is important and decided to implement that in the base class. Then we have a problem. How should this behave? Should the clients keep calling Derived.Foo or Base.Foo. In C# it is guaranteed that Derived.Foo will be the one being called because it will most likely preserve the behaviour expected by the client. However the compiler will issue an warning saying that method Base.Foo was hidden.BUILD: To suppress the warning, the programmer can use the keyword new, and explicitly hide the method Base.Foo. BUILD: Or if he can just override as any virtual method.Classes and StructsConstructorsInstance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initializationCan be overloadedIf a class doesnt define any constructors, an implicit parameterless constructor is createdCannot create a parameterless constructor for a structAll fields initialized to zero/null45If a class defines any constructors, then the implicit parameterless constructor is not created.class B { private int h; public B() { } public B(int h) { this.h = h; }}class D : B { private int i; public D() : this(24) { } public D(int i) { this.i = i; } public D(int h, int i) : base(h) { this.i = i; }}Classes and StructsConstructor InitializersOne constructor can call another with a constructor initializerCan call this(...) or base(...)Default constructor initializer is base()46B.B() is needed because once B.B(int h) was defined, the default parameterless constructor is no longer created.Cant call both : base() and : this() because it would then be ambiguous as to how the base class is constructed.Classes and StructsStatic ConstructorsA static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution orderOnly one static constructor per typeMust be parameterlessclass Foo { ~Foo() { Console.WriteLine(Destroyed {0}, this); }}Classes and StructsDestructorsA destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance, do bookkeeping, etc. Only classes, not structs can have destructorsClasses and StructsDestructorsUnlike C++, C# destructors are non-deterministicThey are not guaranteed to be called at a specific timeThey are guaranteed to be called before shutdownUse the using statement and the IDisposable interface to achieve deterministic finalizationclass Car { string vid; public static bool operator ==(Car x, Car y) { return x.vid == y.vid; }}Classes and StructsOperator OverloadingUser-defined operatorsMust be a static methodClasses and StructsOperator Overloading+-!~truefalse++--Overloadable unary operatorsOverloadable binary operators+-*/!~%&|^==!=

=Classes and StructsOperator OverloadingNo overloading for member access, method invocation, assignment operators, nor these operators: sizeof, new, is, as, typeof, checked, unchecked, &&, ||, and ?:The && and || operators are automatically evaluated from & and |Overloading a binary operator (e.g. *) implicitly overloads the corresponding assignment operator (e.g. *=)

Classes and StructsOperator Overloadingstruct Vector { int x, y; public Vector(x, y) { this.x = x; this.y = y; } public static Vector operator +(Vector a, Vector b) { return Vector(a.x + b.x, a.y + b.y); } ...}class Note { int value; // Convert to hertz no loss of precision public static implicit operator double(Note x) { return ...; } // Convert to nearest note public static explicit operator Note(double x) { return ...; }}Note n = (Note)442.578;double d = n;Classes and StructsConversion OperatorsUser-defined explicit and implicit conversionsClasses and StructsImplementing InterfacesClasses and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interfacepublic interface IDelete { void Delete();}public class TextBox : IDelete { public void Delete() { ... }}public class Car : IDelete { public void Delete() { ... }}TextBox tb = new TextBox();IDelete iDel = tb;iDel.Delete();

Car c = new Car();iDel = c;iDel.Delete();Classes and StructsImplementing Interfacespublic interface IDelete { void Delete();}public interface IFoo { void Delete();}public class TextBox : IDelete, IFoo { public void IDelete.Delete() { ... } public void IFoo.Delete() { ... }}Classes and StructsImplementing InterfacesExplicit interface implementationHandles name collisions