Classes
Classes comprise of members (to hold data essentially) and methods (behaviours).
Fields and Properties
Fields are the actual storage, requiring memory and typically were private. Naming convention _nameProperties are different; These implement means of getting/setting fields. Today you usually just implement the property and behind the scenes the compiler quietly creates the underlying fields for you (following the naming convention _name). Properties have the naming convention Name
Events and Delegates.
Events can be raised (and subscribed to) in order to alert other objects in your (or other) applications that something has happened. If you define a delegate anyone could add themselves to the subscribed list - but they could also wipe out the subscribed list. Safer therefore to use events. Subscribers can only add (subscribe) themselves to listen to your event, or remove themselves from the list. They can't do anything else to the subscribed list.Class Features
Static Classes
Static classes are associated with the type/class and not an instance of the type.E.g. Math.PI. PI is a static property of the class Math.
A static class can have only static members and can't instantiate a static class.
Only one copy of a static class.
This is done for convenience
Sealed Classes
Sealed classes cannot be inherited. This is for performance benefits.String is sealed and cannot be inherited from.
Partial Classes
For extensibilityAllows you to define a class across multiple files - within the same project.
Compiler merges them together into a single class.
Provides extensibility points and is optimized away if no implementation is provided.
Access Modifiers
public - Applies to Class, Member - Meaning: No restrictionsprotected - Member - Access limited to class and derived classes
internal - Class & Member - Access limited to the current assembly (Default of a class)
protected internal - Member - Access limited to the current assembly and derived types
private - Member - Access limited to the class (Default of a member)
Abstract
Applies to a class or membersCannot be instantiated - An abstract class is designated as a base class (e.g. Animal)
Implementation of an abstract method is in the derived class and should use override to implement it.
Virtual
(Implement polymorphism)Override members in a derived class.
Members are non-virtual by default.
Virtual method could have code in the base/parent class (unlike an abstract method).
Regular methods are dispatched based on the type of the variable
Virtual methods are dispatched based on the type of the object
If you don't override a virtual method in the base class, then the definition in the derived class hides or overlays the definition in the base class. To get true polymorphism you need to both mark the base method virtual and the derived method as virtual.
No comments:
Post a Comment