Understanding OOP Concepts With C#

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Understanding OOP concepts with C#

Diploma Awarding Partner


University Partnerships

Copyright © 2019 iNet College. 1


Introduction to OOP
 All functionality is contained in a few modules of code is known as procedural programming or traditional
programming.
 With OOP techniques, you often use many more modules of code, with each offering specific functionality. Also,
each module can be isolated or even completely independent of the others. This modular method of programming
gives you much more versatility and provides more opportunity for code reuse.
 In a more traditional application, the flow of execution is often simple and linear. Applications are loaded into
memory, begin executing at point A, end at point B, and are then unloaded from memory. Along the way various
other entities might be used, such as files on storage media, or the capabilities of a video card, but the main body of
the processing occurs in one place.
 With OOP, things are rarely so linear. Although the same results are achieved, the way of getting there is often very
different. OOP techniques are firmly rooted in the structure and meaning of data, and the interaction between that
data and other data. This usually means putting more effort into the design stages of a project, but it has the benefit
of extensibility.
 OOP often simplifies things by providing an agreement about the approach to data representation, as well as about
the structure and usage of more abstract entities.

Copyright © 2019 iNet College. 2


Class
 Classes are special kinds of templates (called blueprint) from which you can create objects. Each object
contains data and methods to manipulate and access that data. The class defines the data and the
functionality that each object of that class can contain.
 In C#, a class has members: properties, methods, fields(attributes), constructors, destructors, events, and so on.
 There are some OOP principles that need to be satisfied while creating a class. This principle is called as SOLID
where each letter has some specification.
 S (Single Responsibility Principle) – a class should have one, and only one reason to change.
 O (Open Closed Principle) – should be able to extend a classes behavior, without modifying it. (Inheritance)
 L (Liskov Substitution Principle) – derived classes must be substitutable for their base classes. (Polymorphism)
 I (Interface Segregation Principle) – make fine chopped interface instead of huge interface as client cannot be
forced to implement an interface which they don’t use.
 D (Dependency Inversion Principle) – depend on abstractions, not on concretions. (Abstraction)

Copyright © 2019 iNet College. 3


Object
 An object is a building block of an OOP application. This building block encapsulates part of the application, which
can be a process, a chunk of data, or a more abstract entity.
 Objects in C# are created from types, just like the variables, known as class. You can use class definitions to
instantiate objects, which means creating a real, named instance of a class. The phrases instance of a class and
object mean the same thing here; but class and object mean fundamentally different things.
Properties and Fields
 Properties and fields provide access to the data contained in an object. This object data differentiates separate
objects because it is possible for different objects of the same class to have different values stored in properties and
fields. The various pieces of data contained in an object together make up the state of that object.
 Both fields and properties are typed, so you can store information in them as string values, as int values, and so on.
However, properties differ from fields in that they don’t provide direct access to data.
 It is better to provide properties rather than fields for state access because you have more control over various
behaviors. This choice doesn’t affect code that uses object instances because the syntax for using properties and
fields is the same.
 Read/write access to properties can also be clearly defined by an object. Certain properties can be read-only,
allowing you to see what they are but not change them (at least not directly). This is often a useful technique for
reading several pieces of state simultaneously.

Copyright © 2019 iNet College. 4


Object
 Read/write access for properties, you can also specify a different sort of access permission for both fields and
properties, known as accessibility (public, private, etc.).
 One common practice is to make fields private and provide access to them via public properties. This means that
code within the class has direct access to data stored in the field, while the public property shields external users
from this data and prevents them from placing invalid content there.
Methods
 Method is the term used to refer to functions exposed by objects. These can be called in the same way as any other
function and can use return values and parameters in the same way.
 Methods are used to provide access to the object’s functionality. Like fields and properties, they can be public or
private, restricting access to external code as necessary. They often make use of an object’s state to affect their
operations, and have access to private members, such as private fields, if required.

Copyright © 2019 iNet College. 5


Accessibility
 Accessibility is the visibility of the class.
 The default accessibility of a class is internal and for the class members is private.
 The following table lists the accessibility keywords:

Keyword Description
public Visible in the current and referencing assembly.
private Visible inside current class.
protected Visible inside current and derived class.
internal Visible inside containing assembly.
protected internal Visible inside containing assembly and descendent of the current class.

Copyright © 2019 iNet College. 6


Modifiers
 Modifiers refine the declaration of a class.
 The list of all modifiers defined in the table are as follows:

Modifier Description
sealed Class can’t be inherited by a derived class.
static Class contains only static members.
unsafe The class that has some unsafe construct likes pointers.
abstract The instance of the class is not created if the class is abstract.

Copyright © 2019 iNet College. 7


Object’s Life Cycle
 Every object has a clearly defined life cycle and includes two important stages:
 Constructor – When an object is first instantiated it needs to be initialized. This initialization is known as construction and is
carried out by a constructor function, often referred to simply as a constructor.
 Destructor – When an object is destroyed, there are often some clean-up tasks to perform. This is the job of a destructor
function, also known as a destructor.

Constructor
 A constructor is a specialized function that is used to initialize fields or additional tasks.
 All class definitions contain at least one constructor. These constructors can include a default constructor, which is a
parameter-less method with the same name as the class itself.
 A class definition might also include several constructor methods with parameters, known as nondefault
constructors.
 A constructor returns void but does not have an explicitly declared return type.
 Classes can have multiple constructors in the form of default, parameter or both.
 In C#, constructors are called using the new keyword.

Copyright © 2019 iNet College. 8


Object’s Life Cycle
Static Constructor
 When using static members in a class, you might want to initialize these members beforehand. You can supply a
static member with an initial value as part of its declaration, but sometimes you might want to perform a more
complex initialization, or perhaps perform some operations before assigning values or allowing static methods to
execute. You can use a static constructor to perform initialization tasks of this type.
 A class can have a single static constructor, which must have no access modifiers and cannot have any parameters.
 A static constructor can never be called directly; instead, it is executed when one of the following occurs:
1) An instance of the class containing the static constructor is created.
2) A static member of the class containing the static constructor is accessed.
Destructor
 Destructors are used by the .Net Framework to clean up after objects.
 In general, you don’t have to provide code for a destructor method; instead, the default operation does the work for
you.
 However, you can provide specific instructions if anything important needs to be done before the object instance is
deleted.
 Like a constructor, the destructor has the same name as the class except a destructor is prefixed with a tide(~).

Copyright © 2019 iNet College. 9


Inheritance
 Inheritance is one of the most important features of OOP. Any class may inherit from another, which means that it
will have all the members of the class from which it inherits. In OOP terminology, the class being inherited from
(derived from) is the parent class (also known as base class).
 Classes in C# can derive only from a single base class directly, although of course that base class can have a base
class of its own, and so on.
 Inheritance enables you to extend or create more specific classes from a single, more generic base class.
 When using inheritance from a base class, private members of the base class are not accessible from a derived class,
but public members are. However, public members are accessible to both the derived class and external code.
Therefore, if you could use only these two levels of accessibility, you couldn’t have a member that was accessible
both by the base class and the derived class but not external code.
 To get around this, there is a third type of accessibility, protected, in which only derived classes have access to a
member. As far as external code is aware, this is identical to a private member – it doesn’t have access in either case.
 As well as defining the protection level of a member, you can also define an inheritance behavior for it. Members of
a base class can be virtual, which means that the member can be overridden by the class that inherits it. Therefore,
the derived class can provide an alternative implementation for the member. This alternative implementation
doesn’t delete the original code, which is still accessible from within the class, but it does shield it from external
code. If no alternative is supplied, then use the base class implementation of the member.

Copyright © 2019 iNet College. 10


Inheritance
 Base classes may also be defined as abstract classes. An abstract class can’t be instantiated directly; to used it you
need to inherit from it. Abstract classes can have abstract members, which have no implementation in the base
class, so an implementation must be supplied in the derived class.
 Finally, a class may be sealed. A sealed class cannot be used as a base class, so no derived classes are possible.
 There are mainly four types of inheritance:
1) Single level inheritance – there is single base class and a singe derived class.
2) Multi-level inheritance – there is more than one single level of derivation.
3) Hierarchical inheritance – multiple derived class would be extended from base class.
4) Hybrid inheritance – single, multi-level and hierarchical inheritance all together construct a hybrid inheritance.

Copyright © 2019 iNet College. 11


Encapsulation
 Encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.
 Technically in encapsulation, the variables or data of a class are hidden from any other class and can be accessed
only through any member function of own class in which they are declared.
 As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
 Declaring all the fields in the class as private and using properties in the class to set and get the values of variables
can achieve encapsulation.
Advantages of Encapsulation
 Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user
that how the class is stored values in the variables. He only knows that we are passing the values to ace ssors and
variables are getting initialized to that value.
 Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our
requirement. If we wish to make the variables as read-only then we have to only use Get Accessor in the code. If we
wish to make the variables as write-only then we have to only use Set Accessor.
 Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
 Testing code is easy: Encapsulation code is easy to test for unit testing.

Copyright © 2019 iNet College. 12


Polymorphism
 Polymorphism means providing an ability to take more than one form.
 The polymorphism is a combination of two words, one is poly that means “multiple” and another one is morphs
that means “forms”, so polymorphism means many forms.
 In C#, polymorphism provides an ability for the classes to implement different methods through the same name and
it also provides to invoke the methods of derived class through base class reference during runtime.
 There are two kinds of polymorphism:
1) Compile Time Polymorphism – means defining multiple methods with the same name but with different
parameters. By using this, we can perform different tasks with the same method name by passing different
parameters. In C#, this can be achieved by using method overloading and it is also called as early binding or static
binding.
2) Run Time Polymorphism – means overriding a base class method in derived class by creating a similar
function and this can be achieved by using override & virtual keywords in C#. By using this, we can override a
base class method in derived class by creating a method with same name and parameters to perform a different
task. In C#, this can be achieved by using method overriding and it is also called as late binding or dynamic
binding.

Copyright © 2019 iNet College. 13


Abstraction
 Abstraction is used to hide the implementation details and display only essential features of the object.
 In abstraction, by using access modifier we can hide the required details of object and expose only necessary
methods and properties through the reference of object.
 Difference between abstraction and encapsulation:
 Abstraction – it is used to hide unwanted data and show only required properties and methods.
 Encapsulation – it is used to bind data members and member functions into single unit to prevent outsiders to
access it directly.

Copyright © 2019 iNet College. 14


Interface
 Interface is same like class but only different is class can contain both declarations and implementation of methods,
properties and events but interface will contain only the declarations of methods, properties and events that a class
or struct can implement.
 An interface in C# is more like a contract and the class or struct that implements an interface must provide an
implementation for all the members that are specified in the interface definition.
 Generally, C# will not support multiple inheritance of classes but that can be achieved by using interface. In
addition, a structure in C# cannot be inherited from another structure or class but that can be inherited by using
interfaces.
 In C#, an interface cannot be instantiated directly, but it can be instantiated by a class or struct that implements an
interface.
 By default, the members of interface are public and we are not allowed to any other access modifiers. In C#, an
interface can contain methods, properties, events, indexers but it can’t contain constants, fields, operators, instance
constructors, finalizers or types.
 In C#, we can define an interface by using interface keyword.

Copyright © 2019 iNet College. 15


Abstract
 In C#, abstract is a keyword which is used to define classes and class members that are needs to be implemented or
overridden in a derived class.
 We can use abstract modifier with classes, methods, properties, events and indexers.
Abstract Class
 In C#, abstract class is a class which is declared with an abstract modifier. If we define a class with abstract modifier,
then that class is intended only to be used as a base class for other classes.
 An abstract class cannot be instantiated and can contain both abstract and non-abstract members.
 In C#, we should not use a sealed keyword with abstract class because the sealed keyword will make a class as not
inheritable but abstract modifier requires a class to be inherited.
 The class that is derived from abstract class must implement all the inherited abstract methods and accessors.
Abstract Method
 In C#, abstract method is a method which is declared with an abstract modifier. If we define a method with abstract
modifier, then that method doesn’t contain any implementation and method declaration simply ends with
semicolon. Only the derived classes will provide an actual implementation for abstract methods.
 In C#, abstract methods are permitted to declare only within abstract classes.
 We should not use static or virtual modifiers during abstract method declaration.

Copyright © 2019 iNet College. 16

You might also like