Points that we will cover in this post:
- OOP's overview
- Classes and Objects
- Constructor and Destructor
- Function Overloading
- Encapsulation
- Inheritance
- Interface
- Polymorphism
OOP's overview
Object-oriented programming (OOP) is the
core element of the .NET framework.
The fundamental idea behind OOP is to combine
data and methods that operate on that data into a single unit and such units
are called an object. All OOP languages provide mechanisms that help you
implement the object-oriented model. They are encapsulation, inheritance,
polymorphism and reusability. Let's now take a brief look at these concepts.
Class
A class is a template for creating
different objects which defines its properties and behaviors. A class can
contain fields and methods to describe the behavior of an object. It is the
blue print that describes objects.
Class members
A class has different members, and
developers in Microsoft suggest to program them in the following order:
- Namespace: The namespace is a keyword that defines a distinct
name or last name for the class. A namespace categorizes and organizes the
library (assembly) where the class belongs and avoids collisions with
classes that share the same name.
- Class declaration: Line of code where the class name and
type are defined.
- Fields: Set of variables declared in a class block.
- Constants: Set of constants declared in a class block.
- Constructors: A method or group of methods that contains
code to initialize the class.
- Properties: The set of descriptive data of an object.
- Events: Program responses that get fired after a user or
application action.
- Methods: Set of functions of the class.
- Destructor: A method that is called when the class is
destroyed. In managed code, the Garbage Collector is in charge of
destroying objects; however, in some cases developers need to take extra
actions when objects are being released, such as freeing handles or
deallocating unmanaged objects. In .NET, there is no concept of
deterministic destructors. The Garbage Collector will call the Finalize()
method at a non-deterministic time while reclaiming memory for the
application.
Access keywords
Access keywords define the access to class
members from the same class and from other classes. The most common access
keywords are:
- Public: Allows access to the class member from any other
class.
- Private: Allows access to the class member only in the same
class.
- Protected: Allows access to the class member only within the
same class and from inherited classes.
- Internal: Allows access to the class member only in the same
assembly.
- Protected internal: Allows access to the class member only
within the same class, from inherited classes, and other classes in the
same assembly.
- Static: Indicates that the member can be called without
first instantiating the class.
The following sample code illustrates a
sample class in C#:
///Imported namespaces
using System;
/// Namespace:
Consider using CompanyName.Product.ComponentType
namespace DotNetTreats.OOSE.OOP_CSharp {
///Class declaration
public class
employee {
///Fields
private string
_name;
private int
_salary;
///Constants
private const
int anualBonus = 1000;
///Constructor
public employee(){
}
///Properties
public string
Name {
get {
return _name;
}
set {
_name = value;
}
}
public int
Salary {
get {
return _salary;
}
set {
_salary = value;
}
}
/// Event handlers
public event
EventHandler OnPromotion {
add {
}
remove {
}
}
/// Methods
public void
DuplicateSalary()
{
_salary = _salary*2;
}
}
}
Object
Object
is an instance of a class. We can perform set of operations and access
properties of class using object.
Structures
Not
everything in the real world should be represented as a class. Structures are
suitable to represent lightweight objects. Structures can have methods and
properties and are useful for defining
types that act as user-defined primitives, but contain arbitrary composite
fields. The .NET Framework defines some structures such as
System.Drawing.Rectangle, System.Drawing.Point, and System.Drawing.Color.
What is Abstraction?
Where
we use abstract?
How Data hiding is different from abstraction.
Encapsulation and abstraction:
Encapsulation and abstraction is
the advanced mechanism in C# that lets your program to hide unwanted code
within a capsule and shows only essential features of an object. Encapsulation
is used to hide its members from outside class or interface, whereas
abstraction is used to show only essential features.
In C# programming, Encapsulation
uses five types of modifier to encapsulate data. These modifiers are public,
private, and internal, protected and protected internal. These all includes
different types of characteristics and makes different types of boundary of
code.
Encapsulation is the process of hiding irrelevant data from the
user. To understand encapsulation, consider an example of mobile phone.
Whenever you buy a mobile, you don’t see how circuit board works. You are also
not interested to know how digital signal converts into analog signal and vice
versa. These are the irrelevant information for the mobile user, that’s why it
is encapsulated inside a cabinet.
Abstraction is just opposite of Encapsulation. Abstraction is
mechanism to show only relevant data to the user. Consider the same mobile
example again. Whenever you buy a mobile phone, you see their different types
of functionalities as camera, mp3 player, calling function, recording function,
multimedia etc. It is abstraction, because you are seeing only relevant
information instead of their internal engineering.
Inheritance
It means "Reusability".
Inheritance is the process by which one object can import the properties of
another object.
If we want to use the functionality
of one class in to other class then we can inherit this class. Then function
and properties of this class will be accessible in child class.
For example all .NET classes
inherit from the System.Object class, so a class can include new functionality
as well as use the existing object's class functions and properties as well.
C# supports single class inheritance only. What this
means is, your class can inherit from only one base class at a time. This is
not allowed in C#. This will lead to a compile time
What
is Polymorphism?
Overloading
and overriding difference?
Polymorphism means many forms (ability to take more than one
form). In Polymorphism poly means “multiple” and morph means “forms” so
polymorphism means many forms.
In polymorphism we will declare methods with same name and
different parameters in same class or methods with same name and same
parameters in different classes. Polymorphism has ability to provide different
implementation of methods that are implemented with same name.
In Polymorphism we have 2 different types those are
- Compile Time
Polymorphism (Called as Early Binding or Overloading or static binding)
- Run Time
Polymorphism (Called as Late Binding or Overriding or dynamic binding)
Compile Time Polymorphism
Compile time polymorphism means we will declare methods with
same name but different signatures because of this we will perform different
tasks with same method name. This compile time polymorphism also called as early
binding or method overloading.
Method Overloading or compile time polymorphism means same
method names with different signatures (different parameters)
public class
Class1
{
public void
NumbersAdd(int a, int
b)
{
Console.WriteLine(a + b);
}
public void
NumbersAdd(int a, int
b, int c)
{
Console.WriteLine(a + b + c);
}
}
In above class we have two methods with same name but
having different input parameters this is called method overloading or compile
time polymorphism or early binding.
Run Time Polymorphism
Run time polymorphism also called as late binding or method
overriding or dynamic polymorphism. Run time polymorphism or method
overriding means same method names with same signatures.
In this run time polymorphism or method overriding we can
override a method in base class by creating similar function in derived class
this can be achieved by using inheritance principle and using “virtual
& override” keywords.
In base class if we declare methods with virtual
keyword then only we can override those methods in derived class using override
keyword
//Base Class
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base
Class");
}
}
// Derived
Class
public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived
Class");
}
}
// Using base
and derived class
class Program
{
static void
Main(string[] args)
{
// calling the
overriden method
DClass objDc = new
DClass();
objDc.Sample1();
// calling the
base class method
Bclass objBc = new
DClass();
objBc.Sample1();
}
}
Reusability
once a class has been written, created and debugged, it can be
distributed to other programmers for use in their own program. This is called
reusability, or in .NET terminology this concept is called a component or a
DLL. In OOP, however, inheritance provides an important extension to the idea
of reusability. A programmer can use an existing class and without
modifying it, add additional features to it.
Partial
classes:
A partial class splits the definition of a class over two or
more source files. You can create a class definition in multiple files but it
will be compiled as one class.
Suppose you have a "Person" class. That definition
is divided into the two source files "Person1.cs" and "Person2.cs".
Then these two files have a class that is a partial class. You compile the
source code, then create a single class.
Here is a list of some of the advantages of partial
classes:
- You
can separate UI design code and business logic code so that it is easy to
read and understand. For example, you are developing a web application
using Visual Studio and add a new web form then there are two source
files, "aspx.cs" and "aspx.designer.cs".
These two files have the same class with the partial keyword. The ".aspx.cs"
class has the business logic code while "aspx.designer.cs"
has user interface control definition.
- When
working with automatically generated source, the code can be added to the
class without having to recreate the source file. For example, you are
working with LINQ to SQL and create a DBML file. Now when you drag and
drop a table, it creates a partial class in designer.cs and all
table columns have properties in the class. You need more columns in this
table to bind on the UI grid but you don't want to add a new column to the
database table so you can create a separate source file for this class
that has a new property for that column and it will be a partial class. So
that does affect the mapping between database table and DBML entity but
you can easily get an extra field. It means you can write the code on your
own without messing with the system generated code.
- More
than one developer can simultaneously write the code for the class.
- You
can maintain your application better by compacting large classes. Suppose
you have a class that has multiple interfaces so you can create multiple
source files depending on interface implements. It is easy to understand
and maintain an interface implemented on which the source file has a
partial class. Let's see the following code snippet.
5. public interface IRegister
6. {
8. }
9.
10.public interface ILogin
11.{
13.}
14.
16.public partial classUser : IRegister, ILogin
17.{
19.}
20.
22.public partial classUser
23.{
25.}
A partial class or struct may contain a partial method. One
part of the class contains the signature of the method. An optional
implementation may be defined in the same part or another part. If the
implementation is not supplied, then the method and all calls to the method are
removed at compile time.
What
are Static classes?
A
static class
is basically the same as a non-static class, but there is one difference: a
static class cannot be instantiated. In other words, you cannot use the
new keyword
to create a variable of the class type. Because there is no instance variable,
you access the members of a static class by using the class name itself. For
example, if you have a static class that is named
UtilityClass
that has a public method named
MethodA, you call the
method as shown in the following example:
UtilityClass.MethodA();
As is the case with all class types, the type information
for a static class is loaded by the .NET Framework common language runtime
(CLR) when the program that references the class is loaded. The program
cannot specify exactly when the class is loaded. However, it is guaranteed to
be loaded and to have its fields initialized and its static constructor called
before the class is referenced for the first time in your program. A static
constructor is only called one time, and a static class remains in memory for
the lifetime of the application domain in which your program resides.
As is the case with all class
types, the type information for a static class is loaded by the .NET Framework
common language runtime (CLR) when the program that references the class is
loaded. The program cannot specify exactly when the class is loaded.
However, it is guaranteed to be loaded and to have its fields initialized and
its static constructor called before the class is referenced for the first time
in your program. A static constructor is only called one time, and a static
class remains in memory for the lifetime of the application domain in which
your program resides.
The following list provides the
main features of a static class:
Creating a static class is
therefore basically the same as creating a class that contains only static
members and a private constructor. A private constructor prevents the class
from being instantiated. The advantage of using a static class is that the compiler
can check to make sure that no instance members are accidentally added. The
compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and
therefore cannot be inherited. They cannot inherit from any class except
Object.
Static classes cannot contain an instance constructor; however, they can
contain a static constructor. Non-static classes should also define a static
constructor if the class contains static members that require non-trivial
initialization. For more information, see
Static
Constructors (C# Programming Guide).
A non-static class can contain
static methods, fields, properties, or events. The static member is callable on
a class even when no instance of the class has been created. The static member
is always accessed by the class name, not the instance name. Only one copy of a
static member exists, regardless of how many instances of the class are
created. Static methods and properties cannot access non-static fields and
events in their containing type, and they cannot access an instance variable of
any object unless it is explicitly passed in a method parameter.
It is more typical to declare a
non-static class with some static members, than to declare an entire class as
static. Two common uses of static fields are to keep a count of the number of
objects that have been instantiated, or to store a value that must be shared
among all instances.
Static methods can be overloaded
but not overridden, because they belong to the class, and not to any instance
of the class.
Although a field cannot be declared
as static const, a
const field
is essentially static in its behavior. It belongs to the type, not to instances
of the type. Therefore, const fields can be accessed by using the same
ClassName.MemberName notation that is used for static fields. No object
instance is required.
C# does not support static local
variables (variables that are declared in method scope).
Can we have
non static function in static class?
Answer is no
Can we
constructor in static classes?
Yes only static constructor. But
this class will be never instantiated
Can we have
private constructor?
Yes, by doing this means it cannot
be instantiated.
Are private class members inherited to the derived
class?
Yes,
the private members are also inherited in the derived class but we will not be
able to access them. Trying to access a private base class member in the
derived class will report a compile time error.
Interface:
The Interface is basically a contract between an Interface
and a class. In the Interface we do not have implementation of properties and
methods.
The class that implements the Interface or inherits from the
Interface must implement the methods defined in the Interface.
Abstract classes:
If we need to provide common fields
and members to all subclasses, we create an Abstract class. We can create an
abstract class, with the use of the abstract keyword. Abstract classes cannot
be instantiated.
Difference between interface and abstract class
- Interfaces supports multiple inheritance. A
class may inherit several interfaces but can only one abstract class.
- We can declare method in interfaces. But in
abstract classes we can define and declare methods
- Interface are public to all sub classes we
cannot use access modifiers. An
abstract class can contain access modifiers for the subs, functions, properties.
- If various implementations only share method
signatures then it is better to use Interfaces. If various implementations are of the same kind and use common
behavior or status then abstract class is better to use.
- Abstract classes are generally fast to find
actual methods
- No fields can be defined in interfaces. And
abstract class can have fields.
When to prefer an Abstract class
Abstract classes allow you to provide default functionality
for the subclasses. Common knowledge at this point. Why is this extremely
important though? If you plan on updating this base class throughout the life
of your program, it is best to allow that base class to be an abstract class.
Why? Because you can make a change to it and all of the inheriting classes will
now have this new functionality. If the base class will be changing often and
an interface was used instead of an abstract class, we are going to run into
problems. Once an interface is changed, any class that implements that will be
broken. Now if it’s just you working on the project, that’s no big deal.
However, once your interface is published to the client, that interface needs
to be locked down. At that point, you will be breaking the client’s code.
Constructors and Destructors:
Constructors and destructors are special member functions
of classes that are used to construct and destroy class objects. Construction
may involve memory allocation and initialization for objects. Destruction may
involve cleanup and deallocation of memory for objects.
- Constructors
and destructors do not have return types nor can they return values.
- References
and pointers cannot be used on constructors and destructors because their
addresses cannot be taken.
- Constructors
cannot be declared with the keyword virtual.
- Constructors
and destructors cannot be declared const, or volatile.
- Unions
cannot contain class objects that have constructors or destructors.
Constructors and destructors obey the same access rules as
member functions. For example, if you declare a constructor with protected
access, only derived classes and friends can use it to create class objects.
The compiler automatically calls constructors when defining
class objects and calls destructors when class objects go out of scope. A
constructor does not allocate memory for the class object
it’s this pointer refers to, but may allocate storage for more
objects than its class object refers to. If memory allocation is required for
objects, constructors can explicitly call the new operator. During
cleanup, a destructor may release objects allocated by the corresponding
constructor. To release objects, use the delete operator.
Example of Constructor
class C
{
private int x;
private int y;
public C (int i, int j)
{
x = i;
y = j;
}
public void display ()
{
Console.WriteLine(x + "i+" + y);
}
}
Example of Destructor
class D
{
public D ()
{
// constructor
}
~D ()
{
// Destructor
}
}
Behavior of Constructors
in Inheritance:
The sequence of execution will be first base class
constructor will be executed and then derived class constructor
Static Constructors:
This is a new concept introduced in C#. By new here I mean
that it was not available for the C++ developers. This is a special constructor
and gets called before the first object is created of the class. The time of
execution cannot be determined, but it is definitely before the first object
creation - could be at the time of loading the assembly.
Notes for Static Constructors:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor
definition.
Delegates:
Delegates are function pointers. This Refers to a function.
Delegates are simply objects which are holding reference of a method. And we
will invoke this delegate it automatically invoke the functions.
As the delegate refers to a method, the same delegates can
be used to call multiple methods just by changing the method name at the run
time; provided the method (instance or static) match the signature and return
type.
Use a delegate when:
- An eventing design pattern is used.
- It is desirable to encapsulate a static method.
- The caller has no need access other properties,
methods, or interfaces on the object implementing the method.
- Easy composition is desired.
- A class may need more than one implementation of
the method.
Questions:
New
keyword can we use new keyword with function and over ridable function
New methods are expected to hide base methods. The
new modifier specifies that a method is supposed to hide a base method. It
eliminates a warning issued by the compiler. No functionality is changed. But
an annoying warning is silenced.
Here’s a simple implementation in C# without using any
keyword. Do you think it will run fine or show some RUN or COMPILE time errors?
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
Generics
{
class A
{
public void show()
{
Console.WriteLine("Hello: Base
Class!");
Console.ReadLine();
}
}
class B : A
{
public void show()
{
Console.WriteLine("Hello:
Derived Class!");
Console.ReadLine();
}
}
class Polymorphism
{
public static void Main()
{
A a1 = new A();
a1.show();
B b1 = new B();
b1.show();
A a2 = new B();
a2.show();
}
}
}
It is showing some sort of output which means there is
neither run time nor compile time error. But it will definitely show a Warning
to you in your Visual Studio. So what is it and how to remove it. Do you want
to know?
Overriding
+ Hiding | Together
In this snippet, I show how both these methods can work
together in the same snippet. So just go through this and guess the output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Generics
{
class A
{
public virtual void show()
{
Console.WriteLine("Hello: Base Class!");
Console.ReadLine();
}
}
class B : A
{
public override void show()
{
Console.WriteLine("Hello: Derived Class!");
Console.ReadLine();
}
}
class C : B
{
public new void show()
{
Console.WriteLine("Am Here!");
Console.ReadLine();
}
}
class Polymorphism
{
public static void Main()
{
A a1 = new A();
a1.show();
B b1 = new B();
b1.show();
C c1 = new C();
c1.show();
A a2 = new B();
a2.show();
A a3 = new C();
a3.show();
B b3 = new C();
b3.show();
}
}
}
Output will be:

Yes we use new keyword with virtual mathode
https://msdn.microsoft.com/en-us/library/ms173153.aspx