SOFTWARE DEVELOPMENT I 3rd lecture Today Type conversions Three - - PowerPoint PPT Presentation
SOFTWARE DEVELOPMENT I 3rd lecture Today Type conversions Three - - PowerPoint PPT Presentation
SOFTWARE DEVELOPMENT I 3rd lecture Today Type conversions Three main OOP pillars Constructors in depth Classes: Class inheritance fields, properties, methods, actions, delegates, nested types Interfaces Access
Today
- Three main OOP pillars
- Classes:
– fields, properties, methods, actions, delegates, nested types – Access modifiers
- Generics
- SOLID
- Type conversions
- Constructors in depth
- Class inheritance
- Interfaces
- Standard .NET interfaces
– IComparable – IComparer – IEquatable – IEnumerable – ICloneable (and cloning)
- Kahoot
Software Engineering 1. VU MIF
Software Engineering 1. VU MIF
Themes
- #1 WORKING REMOTELY. The past situation brought a lot of challenges for
- rganizations on how to set-up, embrace and support remote work. Your smart
hacks are needed to help utilize offices and resources – how to use them effectively? How to increase trust in each other?
- #2 DIGITAL WORKPLACE. It’s not just about apps, tools or next generation devices.
We are looking into hacks that tackle collaboration, mobility and productivity in the future digital workplace. How to use digital tools in a full capacity? How to increase productivity?
- #3 EMPLOYEE ENGAGEMENT – Stretch your brain with fundamental challenges and
how they should change in the future! How to onboard new employees effectively? How to keep team bonds?
Software Engineering 1. VU MIF
Prizes
- 1st place:
– Oculust Quest S all-in-one gaming system – Amazon gift coupons 5 x 150 Eur.
- 2nd place – Amazon gift coupons 5 x 125 Eur.
- Most creative – Arduino Uno starter kit.
- Register here until 4th of October: https://bit.ly/2XU6oga
Software Engineering 1. VU MIF
OOP basics
- Encapsulation – programming methodology,
– Forbids access to specifics of the class. – Allows modify class properties and fields only through exposed methods.
- Inheritance:
– Possibility to reuse, extend or modify class implementation.
- Polymorphism:
– At run time objects of derived class may be treated as objects of a base class in methods, parameters or collections. Also, derived classes may implement different methods behaviour than base class, if base class methods are marked as virtual
Software Engineering 1. VU MIF
Classes
- Class:
– Description, specifying some sort of object data structure and behavior.
- Single responsibility – classes are created using this principle!
- Class can contain:
– constructor, constants, fields, methods, properties, delegates, classes and more.
Software Engineering 1. VU MIF
SRP (Single responsibility principle)
„A class should only have one reason to change“ ~ „A class should only have one responsibility“
If a class has more than one responsibility, then the responsibilities become coupled. Changes to one responsibility may break the class’ ability to fulfil other responsibilities.
Can be applied to:
- Methods
- Modules
- Etc.
Software Engineering 1. VU MIF
Bad example – what are reasons to change?
Software Engineering 1. VU MIF
Possible reasons to change
What if I decide to read from DB? What if I decide to change validation logic? What if I change generation logic?
Software Engineering 1. VU MIF
Better example
Software Engineering 1. VU MIF
Bad example – many responsibilities
class Customer { public void Add() { try { // Database code goes here } catch (Exception ex) { System.IO.File.WriteAllText(@"c:\Error.txt", ex.ToString()); } } }
Software Engineering 1. VU MIF
Better example
class FileLogger { public void Log(string error) { System.IO.File.WriteAllText(@"c:\Error.txt", error); } } class Customer { private FileLogger _logger = new FileLogger(); public virtual void Add() { try { // Database code goes here } catch (Exception ex) { _logger.Log(ex.ToString()); } } }
Software Engineering 1. VU MIF
Possible inheritance
Inheritance Example None class ClassA { } Unitary class DerivedClass: BaseClass { } None, implementing interfaces class ImplClass: IFace1, IFace2 { } Unitary and implementing interfaces class ImplDerivedClass: BaseClass, IFace1 { }
Software Engineering 1. VU MIF
Access modifiers
Accessibility Description public Access is not restricted. protected Access is limited to the containing class or types derived from the containing class. internal Access is limited to the current assembly (same .dll). Look internal.cs protected internal Access is limited to the current assembly or types derived from the containing class. private Access is limited to the containing type. private protected Access is limited to the containing class or types derived from the containing class within the current assembly.
Software Engineering 1. VU MIF
Default accessibility (1)
- Top
level types (not nested) can
- nly
be internal or public. Default – internal.
Members of Default accessibility Other allowed accessibility levels interface public internal struct private public internal private
Software Engineering 1. VU MIF
Default accessibility (2)
Members of Default accessibility Other allowed accessibility levels enum public internal class private public protected internal private protected internal private protected
Software Engineering 1. VU MIF
Static vs instance
- Static class is in a way the same as non static, difference is that
there is no possibility to create static class object. (no new).
- Static classes should be used, when you don’t need to save state.
- Similar with fields, look static.cs
- Static class can only have static methods, non static class can have
both.
- Memory is divided to three parts when its loaded: Stack, Heap, and
Static (in .NET it is known as High Frequency Heap).
Software Engineering 1. VU MIF
Constructor
- Constructor is a method that is being called when class is being
initialized.
Software Engineering 1. VU MIF
Methods (1)
- Syntax:
modifier returnType name (parameters) { statements; }
- For value types as a parameters the copy of a value is passed, for
reference types as a parameters – reference is passed. Look refvsvalue.cs
Software Engineering 1. VU MIF
Methods (2)
- Method overloading:
– Different signatures (return type is not counted in signature)
- Abstract method:
– Defined method signature, but there is no implementation. – Only possible in abstract class. – Inherit class must implement abstract method (using
- verride).
Look abstractMethod.cs
- Virtual
method: allows
(optional) to
- verride
it and must have implementation.
Software Engineering 1. VU MIF
Methods (3)
- Extensions:
– Possibility to extend standard class. – Syntax: public static type MethodName(this typeToExtend str) – Look extensionMethod.cs – Cannot override standard extension methods: – Works in same namespace or by importing namespace with „using“
Software Engineering 1. VU MIF
Named parameters
- Allows to pass parameters in different order than method signature.
- Brings more clarity.
- Named parameters can be passed after standard ones, but not before.
Software Engineering 1. VU MIF
Optional parameters
- Syntax:
– Providing default (or constant) value to a parameter – „new ValType()“, if parameter is reference type (class) – default(ValType), if parameter is value type (e.g enum or struct).
- Allowed to be used in:
– methods, constructors, indexed properties and delegates
Software Engineering 1. VU MIF
Optional parameters
- Must be placed in the end
- f parameters list.
- If the caller provides an
argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters.
Software Engineering 1. VU MIF
Encapsulation
- OOP encapsulation term means that some entity members, behavior and
fields can be wrapped in a class.
- That is that internal (private) fields are hidden from the user and you can
- nly modify those using exposed (public) methods.
- Encapsulation allows to be loosely coupled from the actual implementation,
and that allows us:
– To change from one type of object to another; – Refactor/change class without changing usages.
Software Engineering 1. VU MIF
Encapsulation
Software Engineering 1. VU MIF
Properties
- Property – method to access private field.
- Can be: public, private, protected, internal or protected internal.
- Can be static – enables to access it without creating instance of a
class.
Software Engineering 1. VU MIF
Auto-properties
- If you don’t need additional logic inside.
- Compiler creates hidden private backing field:
- Properties can have restricted access:
- Look property.cs
Software Engineering 1. VU MIF
Indexer (indexed properties)
- Indexers enable objects to be indexed in a similar manner to
arrays.
- Takes index as a parameter.
- Defined with „this“, has
get and set, just like normal properties:
- Can be used in both class and struct.
- Possible to have only one indexer in class/struct.
- Look indexer1.cs and indexer2.cs
Software Engineering 1. VU MIF
Generics
- Generics: enables specifying
type of class or method only when creating it.
- Advantages: code reusability,
types safe, efficiency (no need for unboxing).
- C# syntax <T> (letter(s) can
be different).
- Look generics1.cs
Software Engineering 1. VU MIF
Generic method
- Accepts specified T type parameters:
- It is possible to have more types
- ref specifies that reference is passed
- Look generics2.cs
Software Engineering 1. VU MIF
Generics
Software Engineering 1. VU MIF
Generics
- Ensure types safety:
– List<string> must be filled with only string values.
- Compiler would display an error if you would try
to add integer to a List<string>. If you would use ArrayList – it would not, because it accepts
- bject.
Software Engineering 1. VU MIF
Generics
Software Engineering 1. VU MIF
Generics
- Faster
than using
- bject
because it prevents boxing/unboxing to happen or casting to required type/value from object.
- Promotes code reusability:
– More: MSDN - When to Use Generic Collections – Look generics3.cs
Software Engineering 1. VU MIF
SOLID
SOLID - design principles for more understandable, flexible and maintainable software.
Software Engineering 1. VU MIF
S – Single responsibility principle (SRP) O – Open/closed principle (OCP) L – Liskov substitution principle (LSP) I – Interface segregation principle (ISP) D – Dependency inversion principle (DIP)
Software Engineering 1. VU MIF
OCP (Open/closed principle)
“You should be able to extend a classes behavior, without modifying it”
~
“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”
Achieved via OOP (e.g. polymorphism) We start thinking about OCP, as soon as there is a need "add one more..."
Software Engineering 1. VU MIF
Bad example
class Customer { public int CustomerType {get; set;} public double GetDiscount(double TotalSales){ { if(CustomerType == 1) { return TotalSales – 100; } else { return TotalSales – 50; } } }
Software Engineering 1. VU MIF
Good example
Software Engineering 1. VU MIF
Bad example
- AreaCalculator
not closed for modification – if logic change is needed, code change is needed
- e.g. it is not possible to
adress logic change with adding (not changing) the code (not
- pen
for extension).
Software Engineering 1. VU MIF
Good example
Software Engineering 1. VU MIF
LSP (Liskov substitution principle)
"objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program“ ~ “ subtype behavior should match base type behavior as defined in the base type specification” In simple terms: Derived classes must be substitutable for their base classes.
Software Engineering 1. VU MIF
Example
public class Rectangle { public int Width { get; protected set; } public int Height { get; protected set; } public void SetWidth(int width) => Width = width; public void SetHeight(int height) => Height = height; public int GetArea() { return Width * Height; } } public class Square : Rectangle { public void SetWidth(int width) { Width = width; Height = width; } public void SetHeight(int height) { Width = height; Height = height; } } Software Engineering 1. VU MIF
public class LspTest { private static Rectangle CreateRectangle() { return new Square(); } public static void Main(string[] args) { Rectangle rect = CreateRectangle(); rect.SetWidth(5); rect.SetHeight(10); // User assumes that rect is a rectangle. // They assume that they are able to set the width and height as for the base class Assert.AreEqual(rect.GetArea(), 50); // This check fails for a square! We get 100 } } Software Engineering 1. VU MIF
LSP Checklist
- No new exceptions should be thrown in derived class: If your base
class threw ArgumentException then your subclasses are only allowed to throw exceptions of type ArgumentException or any exceptions derived from it. Throwing IndexOutOfRangeException is a violation of LSP.
- Pre-conditions cannot be strengthened: Assume your base class works
with a member int. Now your subtype requires that int to be positive. This is strengthened pre-conditions, and now any code that worked perfectly fine before with negative ints is broken.
- Post-conditions cannot be weakened: Assume your base class required
all connections to database to be closed before the method returned. In your subclass you overrode that method and left connection open for further reuse.
Software Engineering 1. VU MIF
ISP (Interface segregation principle)
“Clients should not be forced to implement interfaces they do not use”
Software Engineering 1. VU MIF
Bad example
– All code needs to be recompiled for even the smallest changes. – What if device wants only to print? – This is a fat interface.
Software Engineering 1. VU MIF
Better example
Software Engineering 1. VU MIF
ISP summary
- We favor:
– Composition instead of Inheritance
- Separating by roles (responsibilities)
– Decoupling over Coupling
- Not coupling derivative classes with unneeded responsibilities inside a monolith
Software Engineering 1. VU MIF
DIP (Dependency inversion principle)
“Depend on abstractions, not on concretions” – High level modules should not depend upon low level
- modules. Both should depend upon abstractions.
– Abstractions should not depend upon details. Details should depend upon abstractions.
Software Engineering 1. VU MIF
SOLID: DIP
Dependency injection – most common way to implement DIP. Others:
- Service Locator
- Delegates
- Events
- Etc.
Software Engineering 1. VU MIF
Types conversion (1)
- Widening vs narrowing:
– Widening: type that we are converting to can store more values than type from which we are converting (short -> int). – Narrowing: vice versa(int -> short).
- C# does not throw an exception, if narrowing
conversion fails for integers or floating point numbers.
– For integer values value is decreased – For floating point numbers infinity value is set.
Software Engineering 1. VU MIF
Converting integer values
Software Engineering 1. VU MIF
Types conversion (2): solutions
- Integers:
using checked statement, which throws OverflowException
- Integers: project settings configuration:
- Properties -> Build tab -> Advanced -> Check For Arithmetic Overflow (true).
- Disadvantage – code does not reflect program behavior.
- Floating point numbers:
Software Engineering 1. VU MIF
Implicit vs explicit conversion
- Implicit: conversion without using additional code.
- Explicit: using additional code (like cast or parsing)
methods.
- Converting
floating point numbers to integers, everything after “.” is cut:
– (int)10.9 returns 10.
Software Engineering 1. VU MIF
Reference types conversion
- Reference types conversion to a base class or interface is possible implicitly.
- If Employee class inherits from Person class, then Employee object can be
converted to Person object implicitly:
Software Engineering 1. VU MIF
Reference types conversion
- Reference types conversion to a base class or interface does not change the
actual value, just makes it look as a new type.
– person1 is Person type variable, but points to Employee object. – Code can use person1 object as Person type, but in memory it stays as Employee type object.
- Look refConversion.cs
Software Engineering 1. VU MIF
IS
- is
returns true, if
- bjects
are compatible (if casting/conversion is possible)
- „person is Employee“ returns true not only when
person is Employee type, but also when person is Manager type (because Manager is Employee)
Software Engineering 1. VU MIF
AS
- as
- perator
work as cast. If conversion fails, as returns null instead of throwing an exception.
- Syntax suggar
- Arrays conversion: arrayCast1.cs
– cast does not create new arrays! – As this would not create as well:
Software Engineering 1. VU MIF
Parse and tryParse
- All primitive C# data types (int, bool, double, and so
forth) has Parse method.
- bool.Parse("yes") will throw FormatException
- bool.Parse("true") returns bool type true value.
- parse
throws exceptions, tryParse returns
- ut
parameter containing parse result or null (if parse failed).
- Parse requires pre-validation of data.
- Difficult to work with different culture information.
- Look parsing.cs
Software Engineering 1. VU MIF
System.Convert
- “bankers rounding”:
– Rounds to the closest integer value. – If it ends with .5, then it rounds to closest even number.For example below would result in 10:
- You can also do it like that:
ToBoolean ToByte ToChar ToDateTime ToDecimal ToDouble ToInt16 ToInt32 ToInt64 ToSByte ToSingle ToString ToUInt16 ToUInt32 ToUInt64
Software Engineering 1. VU MIF
Boxing/unboxing (1)
- Process when value type is converted to object or interface type, which value types
implements.
– Lets say we are converting int or bool (or similar) to object type, or to interface, which is supported by that value type (e.g. struct).
- Unboxing is a process, when boxed value is converted back from reference type to value
type.
- Both processes are slow:
– Boxing – because of heap usage – Unboxing – because of casting
Software Engineering 1. VU MIF
Boxing/unboxing (2)
- Boxing is implicit; unboxing is explicit.
- Sometimes is happens silently:
Software Engineering 1. VU MIF
Boxing/unboxing (3)
- What will be printed out?
1 and 2 2 and 5
Software Engineering 1. VU MIF
Constructors
- Constructor – it is a method that is being called first when an instance of a
class or struct being created.
- Same for static constructor – but only for the first time.
- What constructors can do:
- 1. Overload
Software Engineering 1. VU MIF
Constructor
- What constructors can do:
- 2. Call base class constructor using keyword : base
(look constructor(intro).cs)
- 3. If there are no explicit constructor defined – the
default constructor is being created implicitly:
- There are no parameters.
- Field values are initialized to default value.
- Causes problems when changes are needed.
Software Engineering 1. VU MIF
Constructor
- What constructors can do:
- 4. Call same class different constructors using: this
Look constructor(good).cs constructor(bad).cs
Software Engineering 1. VU MIF
Constructor
- What constructors cant do:
- 5. Can not call multiple other constructors.
Look constructor(bad2).cs, constructor(good2).cs
Software Engineering 1. VU MIF
Can constructor be non-public?
Software Engineering 1. VU MIF
Constructors
What constructors can do:
- 6. Private/public constructors:
1. Public is standard 2. Private constructors are not allowed to be called from other classes, so if we want to create an instance of such class, there is a special implementation that we have to provide.
Look singleton.cs
Software Engineering 1. VU MIF
Software Engineering 1. VU MIF
What is still wrong with this implement- ation?
Software Engineering 1. VU MIF
Best way to implement singleton
Software Engineering 1. VU MIF
Constructors
What constructors can do:
- 7. Static constructor (Look static.cs)
– Is called implicitly when:
- Class instance is created
- Class static fields or methods are used for the first time
– Class can have only one static constructor – Has to be parameter-less, becase CLR is calling it – Can access only static fields/methods of this class – Static constructor does not have access modifiers – Slow
Software Engineering 1. VU MIF
Software Engineering 1. VU MIF
Initializer
- Explicit creation of an object by setting all the properties
manually.
- Only the standard constructor is called
- Example in the next slide
Software Engineering 1. VU MIF
Software Engineering 1. VU MIF
Questions about constructors?
Software Engineering 1. VU MIF
Inheritance
C# allowed C# not allowed:
Software Engineering 1. VU MIF
Multiple inheritance
Diamond problem:
If A has a method, which B and C classes have overridden, but D did not, then which method will D inherit – from B or from C? From A method is called successfully, but from D – not necessarily.
C# solution: interface
Software Engineering 1. VU MIF
Interface
- Interface
exposes a contract, specifying characteristics that a class must implement.
- Can state required: properties, methods and
actions.
- Interface can not contain any static members
- Interface can not have implementation of the
methods (different from abstract class, because abstract class can have implementation).
Software Engineering 1. VU MIF
Interface
- Since it is similar to inheritance, sometimes it is
being called interface inheritance
- Class can inherit from ONE base class, and
MANY interfaces
- Look interface.cs – TeachingAssistant
Software Engineering 1. VU MIF
Can a class implement two interfaces which has methods with same signatures?
Software Engineering 1. VU MIF
Explicit and implicit interface implementation
- If class implements an interface explicitly, then to access
implemented method you will need a object of interface type, if and interface is implemented implicitly – then you can access method with class type object.
- Explicitly implementing interface requires to write interface
method before method name like:
– void Interface.Method
- In interface.cs look at TeachingAssistant3 which implements
Istudent interface implicitly, and TeachingAssistant4 – explicitly.
Software Engineering 1. VU MIF
Software Engineering 1. VU MIF
Explicit and implicit interface implementation
- Explicit is better, because:
– When working with interface type there is no coupling with a class that implements it.
- Loose coupling allow to scale and change system easier.
– You can have members in your class with same names as in implemented interface:
- If we have a class with property Name, and we want to
implement interface, which has in a contract property Name – we can do it by using explicit interface implementation.
Software Engineering 1. VU MIF
Explicit and implicit interface implementation
- If you are implementing interface implicitly then the
methods will be available for class that implements this interface type objects, and for interface type objects. Sometimes this is not a desired functionality.
- If you are implementing interface explicitly, then access
modifier must be private, because your method can
- nly be accessed via interface.
- When implementing explicitly, we don’t have duplicate
names problems.
- In reality – 90% of implicit implementation.
Software Engineering 1. VU MIF
Interface delegation
- If both Student and TeachingAssistant implements IStudent
interface, then both have a code,which ensures that contract is fulfilled.
- Duplication of code can be avoided by using interface delegation.
– That means that implementation of interface in TeachingAssistant class is being delegated to Student class.
Software Engineering 1. VU MIF
Interface delegation
- In the delegation process a object of type Student is being
created in TeachingAssistant class.
– When TeachingAssistant object has to perform methods, which are in IStudent interface, then Student object is called to do that.
- Look interface.cs: TeachingAssistant (bad, because of
code duplication), TeachingAssistant2
Software Engineering 1. VU MIF
Indexers in interfaces
- Differs from indexers in the
class:
– No access modifiers. – No implementation.
- Class can implement multiple
interfaces with indexers only if interfaces are being implemented explicitly.
Software Engineering 1. VU MIF
Interface is a TYPE
- You can specify it as a parameter to a method
– interface2.cs – takeSpeaker() – If you are passing a class object, that implement an interface, then this object is implicitly being casted to a interface type.
- Return type can be an interface:
– interface2.cs – giveSpeaker()
- Casting
- perators,
to check if interface type is implemented:
– AS: ICat cat = objSomething as ICat; – IS: if (possibleCat is ICat)
Software Engineering 1. VU MIF
Software Engineering 1. VU MIF
Interfaces advantages
- Question: why should we define interface, implement it in a class
and then create interface type of object, instead of class type
- bject?
- Answer:
Software Engineering 1. VU MIF
Generic Interface
- Interface can be generic (have a type passed as parameter)
public class Farmer : IRememberMostRecent<Joke>
- Class can only implement generic interface, if the class itself is
generic.
– In that case type to an interface is passed when constructing class: public class Dog<T> : ICanEat<T>
- Look interfaceGeneric.cs
Software Engineering 1. VU MIF
Generic Interface
- where is used to specify constraints of the types
- new() specifies that new instances can be created
Software Engineering 1. VU MIF
Standard interface implementation
- Benefit – contract implementation
- .NET behaves “better” with types, that implement:
– IComparable interface, Array.Sort() method can sort an array of that class members. – IEquatable interface, then list.Contains() can check, whether an object is really in the list(instead of checking if same pointer is in the list)
Software Engineering 1. VU MIF
IComparable
- Used for comparing this object to a given object.
- Has one method: CompareTo (one param., obj)
- Has both simple and generic version
Value Meaning Negative This instance precedes obj in the sort order. Zero This instance occurs in the same position in the sort order as
- bj.
Greater than zero
This instance follows obj in the sort order.
Software Engineering 1. VU MIF
IComparable
- Simple:
look IComparable.cs
- Generics:
Errors better seen by compiler
Software Engineering 1. VU MIF
IComparer
- IComparable<T> says I’m comparable.
- IComparer<T> says I’m comparer.
- Method: compare(two params)
Value Meaning Less than zero First object is less than the second. Zero Both object are equal. Greater than zero First object is more than the second.
Software Engineering 1. VU MIF
IComparer
- Look
IComparer.cs
Software Engineering 1. VU MIF
IEquatable
- Is used for comparing if two objects are equal.
- Has method Equals.
- Generic collections: List, Dictionary, Stack, Queue
(etc.) has Contains method, which compares objects for equality.
- If
Iequatable interface is implemented then List.Contains check by using our implemented Equals method.
- Microsoft recommends that every class that has a
possibility to be added to a list would implement IEquatable interface.
Software Engineering 1. VU MIF
IEquatable
- If IEquatable<> would be removed – Contains method would
not work.
- Look IEquatable.cs
Software Engineering 1. VU MIF
IEnumerable
- Allows to iterate (e.g. using foreach) through collection
- Has simple and generic version:
Software Engineering 1. VU MIF
IEnumerable
- Has method GetEnumerator, which returns an object,
which implements an interface IEnumerator.
- IEnumerator has:
– Current property, which returns current object from the list – MoveNext method, which moves enumerator one position forward. – Reset which moves enumerator to the initial position. – Dispose (only generics) – inherited from IDisposable.
- Look IEnumerator.cs
Software Engineering 1. VU MIF
IEnumerable
- Can be simplified with yield. Look Ienumerable*.cs
- Must:
– Return IEnumerable type – Be called from iteration loop(e.g foreach)
Software Engineering 1. VU MIF
Software Engineering 1. VU MIF
ICloneable
- From JAVA lectures: new object copy creationis
when object is same type as a type that it is being cloned from and has same state.
- Possible:
– Shallow cloning – Deep cloning
- C#: class that implements ICloneable interface must
implement Clone method.
– Returns cloned object (seriously, object type)
Software Engineering 1. VU MIF
ICloneable
- Deep vs shallow (Look ICloneable.cs)
Software Engineering 1. VU MIF
ICloneable
- Since Clone method returns object type object, then whoever called Clone
method has to take care of casting returned object to required type.
- Implementation is hidden (deep vs shallow):
– Microsoft does not recommend to implement Icloneable for exposed APIs, because consumers will not know how your Clone method will behave. – More: MSDN ICloneable Interface.
Software Engineering 1. VU MIF
Other popular .NET interfaces
- IQueryable (or IQueryProvider): allows to form queries for datasources, that are
queryable.
- INotifyPropertyChange: is used to display data in WPF, Windows Forms and
Silverlight applications.
- IEqualityComparer (similar to IEquatable)
- IList and ICollection: for collections
- IDictionary: for collections, in which you can search using key/value principle.
- ISerializable – allows for an object to control how it is being serialized/deserialized.
- IFormatter / IFormatProvider – used for formatting.
Software Engineering 1. VU MIF
Literature for reading
- A must: C# in depth. Why Properties Matter (online)
- Types (C# Programming Guide). MSDN
- MCSD sertification toolkit:
– 3rd chapter second side – 4th chapter. Converting between types. – MSDN: When to Use Generic Collections
- More: MSDN - When to Use Generic Collections
Software Engineering 1. VU MIF
Literature for own reading
- MCSD sertification toolkit:
– 5th chapter until “Managing object lifecycle”
- MSDN
- MSDN: Boxing and Unboxing (C# Programming Guide)
- On you own: IEnumerable and IEnumerator
– How simple and generic version are different?
Software Engineering 1. VU MIF
Next time
- Software system construction.
- Key goals and challenges.
- Business needs analysis.
- Software system modification and maintenance (introduction)
Software Engineering 1. VU MIF
Questions
Software Engineering 1. VU MIF