Object Oriented Programming in C#
Object Oriented Programming in C#
NET Technology
Theory 1: Object Oriented Programming in C#
Objectives
Objectives
Use Constructors In C#
Use Destructors In C#
Explain the working of Garbage Collector
Objectives
Discuss Polymorphism
Discuss Properties
Discuss Indexers
The Object-Oriented methodology focuses on data rather than processes, with programs composed of self-sufficient modules (objects) each containing all the information needed to manipulate its own data structure. This is in contrast to the existing modular programming which had been dominant for many years that focused on the function of a module An object-oriented program may thus be viewed as a collection of cooperating objects, as opposed to the conventional model, in which a program is seen as a list of tasks (subroutines) to perform
Class Object Instance Method Message passing Inheritance Abstraction Encapsulation Polymorphysm De-coupling
1. What is a class?
A class define the abstract characteristics of a thing (object), including the thing's characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features). For example, the class Dog would consist of traits shared by all dogs, such as:
Breed and fur color (characteristics), and The ability to bark and sit (behaviors)
1. What is a class?
In C#.NET, classes are declared using the keyword class, as shown in the following example:
2. Members of a class
The members of a class type are divided into the following categories:
Constants Fields Methods Properties Events Indexers Operators Constructors Destructors Types
Properties can be recognize by IDEs (such as Visual Studio.NET) but public fields Properties are the hybrid of fields and methods A property is like a clockknob: when you turn it, the hour hand and the minute hand and the second hand are automatically adjusted
2.2. Constructor
Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read. If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values Static classes and structs can also have constructors
2.3. Destructor
Destructors cannot be defined in structs. They are only used with classes. A class can only have one destructor. Destructors cannot be inherited or overloaded. Destructors cannot be called. They are invoked automatically. A destructor does not take modifiers or have parameters. The destructor implicitly calls Finalize on the base class of the object.
2.4. Indexers
Indexers allow you to index a class or a struct instance in the same way as an array An indexer is declared like a property except that the name of the member is this followed by a parameter list written between the delimiters [ and ]
Indexer example
BEFORE
Indexer example
3. Access Modifiers
Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers:
Public: The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members Protected: The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member. Internal: Internal members are accessible only within files in the same assembly. A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. Private: The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared. Nested types in the same body can also access those private members.
In .NET framework 2.0 or higher, Microsoft introduces a very new modifier named partial. Before, the definition a a class must be placed in a single source file. But now, with partial modifier, It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled
When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously. When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio
4. What is an Object?
An Object is a pattern of a class. Exp: The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have; the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur.
4. What is an Object?
In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects and can be viewed as an independent 'machine' with a distinct role or responsibility. The actions (or "operators") on these objects are closely associated with the object.
5. What is an Instance
The instance is the actual object created at runtime (and placed in RAM). The set of values of the fields and properties of a particular object is called its state
7. static keyword
The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors But static keyword cannot be used with indexers, destructors, or types other than classes.
7. static keyword
The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created. A constant is implicitly a static member. A static member cannot be referenced through an instance. Instead, it is referenced through the type name
8. Nested Classes
II. Encapsulation
1. What is encapsulation?
Encapsulation is the hiding of the internal mechanisms and data structures of a software component behind a defined interface, in such a way that users of the component (other pieces of software) only need to know what the component does, and cannot make themselves dependent on the details of how it does it. For example, the Dog class has a bark() method. The code for the bark() method defines exactly how a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie's friend, however, does not need to know exactly how she barks.
The purpose of encapsulation is to achieve potential for change: the internal mechanisms of the component can be improved without impact on other components, or the component can be replaced with a different one that supports the same public interface. Encapsulation also protects the integrity of the component, by preventing users from setting the internal data of the component into an invalid or inconsistent state.
Encapsulation reduces system complexity and thus increases robustness, by limiting the interdependencies between software components
III. Inheritance
Inheritance - Examples
Overloading is the technical term for declaring two or more methods in the same scope with the same name
By specifying different number of parameters By specifying different types of parameters
4. Operator Over-loading
Like C++, C# allows you to overload operators for use on your own classes. This makes it possible for a user-defined data type to look as natural and be as logical to use as a fundamental data type To overload an operator, you write a function that has the name operator followed by the symbol for the operator to be overloaded
Sometimes derived class members have the same name as a corresponding base class member. In this case, the derived member is said to be "hiding" the base class member When hiding occurs, the derived member is masking the functionality of the base class member. Users of the derived class won't be able to see the hidden member; they'll see only the derived class member
7. base keyword
The base keyword is used to access members of the base class from within a derived class:
Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class.
A base class access is permitted only in a constructor, an instance method, or an instance property accessor. It is an error to use the base keyword from within a static method.
8. sealed keyword
When applied to a class, the sealed modifier prevents other classes from inheriting from it You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
In the following example, Z inherits from Y but Z cannot override the virtual function F that is declared in X and sealed in Y.
8. sealed keyword
Notes:
When you define new methods or properties in a class, you can prevent deriving classes from overriding them by not declaring them as virtual. It is an error to use the abstract modifier with a sealed class, because an abstract class must be inherited by a class that provides an implementation of the abstract methods or properties. When applied to a method or property, the sealed modifier must always be used with override. Because structs are implicitly sealed, they cannot be inherited.
8. new keyword
IV. Polymorphism
Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism means many forms Understanding Polymorphism is crucial to any OO language professional , be it a Java , C++ or C# programmer
If a Dog is commanded to speak(), it may emit a bark, while if a Pig is asked to speak(), it may respond with an oink. Both inherit speak() from Animal, but their subclass methods override the methods of the superclass, known as overriding polymorphism We implement polymorphism by using virtual and override keywords
Polymorphysm example
V mt hnh thc, i s u vo ca hm Speak phi c kiu l Animal, v khi hm ny c gi, th phng thc Speak ca Animal s c gi v s khng in ra ni dung g Nhng thc t, khi truyn i s u vo cho hm Speak, lc l Pig, lc l Dog, th hm Speak li lc th gi hm Speak ca Pig, lc th li gi hm Speak ca Dog => Chnh v l do ny, hm Speak c gi l a hnh
4. Why polymorphism?
Why include polymorphism in a programming language? Because it significantly reduces programming effort. In particular, polymorphism allows you to write one method for a variety of types, rather than to write one method per type
Abstraction (from the Latin abs, meaning away from and trahere, meaning to draw) is the process of taking away or removing characteristics from something in order to reduce it to a set of essential characteristics In object-oriented programming, abstraction is one of three central principles (along with encapsulation and inheritance)
Through the process of abstraction, a programmer hides all but the relevant data about an object in order to reduce complexity and increase efficiency
Abstract base classes are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. In C#, the abstract modifier is used to declare an abstract class
3. Interfaces
An interface is a collection of method definitions (without implementations) and constant values. An interface is like a pure abstract base class Notes:
A class that implements a particular interface must implement the members listed by that interface
The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs
The biggest difference between an abstract class and an interface is: A class may implement an unlimited number of interfaces, but may inherit from only one abstract