Better Understanding of
OOP Using C#
Chandan Gupta Bhagat
“Write shy code - modules that don't reveal
anything unnecessary to other modules and that
don't rely on other modules' implementations.”
Andy Hunt & DaveThomas
General Overview
• Classes and Objects
• Functions
• Constructors
• Destructors
• Other Members
Classes and Objects
• Classes are blueprints for Object.
• Objects are instance of classes.
using System;
namespace NameSpace
{
<access_modifier> class ClassName
{
<access_modifier> DataMembers
Constructors
<access_modifier> <return_type> Functions
Destructors
}
}
Classes and Objects
Access Modifiers
•public
•private
•protected
•internal
•protected internal
Classes and Objects
MyClass myObject_One=new MyClass();
MyClass myObject_Two=new MyClass();
Or
var myObject_One=new MyClass();
var myObject_Two=new MyClass();
Functions
<access_modifier> <return_type> Functions (<Parameters>)
{
//Function Logic codes here
}
• return_type is void => write return; or don’t write anything
• return_type is other than void => return object of the return_type
• Parameters can be of any number
• Function Overloading (inside the same class with same name but different
signature):
• Add(int a, int b) => a + b;
• Add(int a, int b, int c) =>a + b + c;
Constructors
• a special method that is used to initialize a newly created object and is called
just after the memory is allocated for the object.
public class ClassName
{
private int _number;
public ClassName() //parameterless constructor
{
_number=10;
}
public ClassName(int number) //parameterized constructor{
_number=number;
}
}
ClassName myObject_One=new MyClass(); //the variable number has the value 10
ClassName myObject_Two=new MyClass(2); //the variable number has the value 2
Destructors
~ClassName()
{ }
• Destructors are invoked automatically, and cannot be invoked explicitly.
• Destructors cannot be overloaded.Thus, a class can have, at most, one destructor.
• Destructors are not inherited.Thus, a class has no destructors other than the one,
which may be declared in it.
• Destructors cannot be used with structs.They are only used with classes.
• An instance becomes eligible for destruction when it is no longer possible for any
code to use the instance.
• Execution of the destructor for the instance may occur at any time after the
instance becomes eligible for destruction.
• When an instance is destructed, the destructors in its inheritance chain are called,
in order, from most derived to least derived.
Data Members
• Constants representing constant values
• Fields representing variables
• Properties that define the class features and include actions to fetch and
modify them
• Events generated to communicate between different classes /objects
• Indexers that help in accessing class instances similar to arrays
• Operators that define semantics when used in expressions with class
instances
• Static constructor to initialize the class itself
• Types that are local to the class (nested type)
Abstraction and Encapsulation
Encapsulation
• Encapsulation is the process of hiding irrelevant data from the user.
• These are the irrelevant information for the mobile user, that’s why it is
encapsulated inside a cabinet.
• To understand encapsulation, consider an example of a 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 the analog
signal and vice versa.
Encapsulation
public class Rectangle
{
private float _length;
private float _breadth;
public float Area
{
get{return _length * _breadth;}
}
public float Perimeter
{
get{return 2*(_length + _breadth);}
}
}
• The Encapsulation fields of a class basically can
be write-only or can be read-only.
• A Encapsulated class can have control over in its
fields.
• A class can change data type of its fields
anytime but users of this class do not need to
change any code.
Abstraction
• Abstraction is just opposite of Encapsulation.
• Abstraction is a mechanism to show only relevant data to the user.
• It is an abstraction because you are seeing only relevant information instead
of their internal engineering.
• Consider the same mobile example again. Whenever you buy a mobile
phone, you see their different types of functionalities as a camera, mp3
player, calling function, recording function, multimedia etc.
Abstraction
public abstract class Shape
{
private float _area;
private float _perimeter;
public float Area
{
get{return _area;}
set{_area = value;}
}
public float Perimeter
{
get{return _perimeter;}
set{_perimeter = value;}
}
public abstract void CalculateArea();
public abstract void CalculatePerimeter();
}
Inheritance
• Allows us to define a class in terms of another class, which makes it easier to
create and maintain an application.
• Provides an opportunity to reuse the code functionality and speeds up
implementation time.
• inherit data and functions from multiple base classes or interfaces.
• Classes in Inheritance
• Base Class :The Origin Classes
• Derived Classes : Derived from base class
• Sealed Classes :This classes are the last of their kind. Cannot derived further
Inheritance
• Example :
• class A is the origin class having the public member One, protected memberTwo and
private memberThree
• class B : A this means B is derived from A having public member Four
• class C : B this means C is derived from B
• sealed class D : A Now D is derived from A and D is last of its species.
• In this example, when we create an instance of C “Obj_c”, the constructor of
hierarchy A is called first, then B and then C.
• public members are accessible from the object of C, i.e. Member One can be
accessible. We can use Obj_c.One
• Protected members are public inside the class C but not accessible outside the
Object of C. i.e. we can useTwo Inside the Class C but Obj_c.Two is not accessible
• private members are private only inside the class and cannot be used outside any
classes. We cannot use memberThree not Obj_c.Three is notValid.
Inheritance
//Base class or Parent class.
public class Shape
{
public Shape(double Length , double Breadth)
{
this.Length=Length;
this.Breadth=Breadth
}
protected double Length;
protected double Breadth;
public void ShowDim()
{
Console.WriteLine(“Length and Breadth” +
Length + " and " + Breadth);
}
}
//Derived class or Child class.
public class Rectangle : Shape
{
public Rectangle (double Length , double
Breadth) : base( Length , Breadth)
{
}
public double Area()
{
return Length * Breadth;
}
public double Perimeter()
{
return 2* ( Length + Breadth );
}
}
Polymorphism
• Polymorphism refers to the ability to present the same interface for
different forms.
• Polymorphism is often expressed as 'one interface, multiple functions’.
• Polymorphism can be static or dynamic.
• Static : the response to a function is determined at the compile time.
• Dynamic : it is decided at run-time.
• Static Polymorphism
• Function overloading
• Operator overloading
• Dynamic polymorphism is implemented by abstract classes and virtual
functions.
Polymorphism
• Dynamic polymorphism is implemented by abstract classes and virtual
functions.
• When you have a function defined in a class that you want to be implemented in an
inherited class(es), you use virtual/abstract functions.
• The virtual functions could be implemented differently in different inherited class and
the call to these functions will be decided at runtime.
• The derived class needs to be overridden in case of any changes to be done from base
classes.
Polymorphism
abstract class Shape {
public abstract int area();
}
--OR--
public class Shape {
public virtual int area() {
return 0;
}
}
public class Rectangle: Shape {
private int length;
private int width;
public Rectangle( int a = 0, int b = 0) {
length = a;
width = b;
}
public override int area () {
Console.WriteLine("Rectangle class area
:");
return (width * length);
}
}
Interface And Abstract Classes
Interface Abstract Class
Supports multiple inheritance Does not support multiple inheritance
Does not contain data members Contains data members
No Constructors Contains constructors
Contains only signature of members Contains both complete and incomplete members
Cannot have access modifiers (all assumed public) Can have access modifiers for the functions,
members
Members cannot be static Only complete members can be static
Interface
• An interface is a contract
• An interface is an empty shell
• Implementing an interface consumes very little CPU
// A motor vehicles should look like this:
interface MotorVehicle
{
void run();
int getFuel();
}
Abstract Class
• Abstract classes, unlike interfaces, are classes
• More expensive to use, because there is a look-up to do when you inherit
from them.
• You can define a behavior for them.
abstract class MotorVehicle{
int fuel;
int getFuel() => fuel;
abstract void run();
}
Extending a Class
• Extension methods enable you to "add" methods to existing types without
creating a new derived type.
• Extension methods are a special kind of static method.
• They are called as if they were instance methods on the extended type.
• Define a static class to contain the extension method.
• Implement the extension method as a static method with at least the same
visibility as the containing class.
• The first parameter of the method specifies the type that the method
operates on; it must be preceded with the this modifier.
• Call the methods as if they were instance methods on the type.
Extending a Class
public static class MyExtensions {
public static int WordCount(this String str,<parameters>){
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
string s = "Hello WebinarforallNepal";
int i = s.WordCount(<parameters>);
Thank you!

Better Understanding OOP using C#

  • 1.
    Better Understanding of OOPUsing C# Chandan Gupta Bhagat
  • 2.
    “Write shy code- modules that don't reveal anything unnecessary to other modules and that don't rely on other modules' implementations.” Andy Hunt & DaveThomas
  • 3.
    General Overview • Classesand Objects • Functions • Constructors • Destructors • Other Members
  • 4.
    Classes and Objects •Classes are blueprints for Object. • Objects are instance of classes. using System; namespace NameSpace { <access_modifier> class ClassName { <access_modifier> DataMembers Constructors <access_modifier> <return_type> Functions Destructors } }
  • 5.
    Classes and Objects AccessModifiers •public •private •protected •internal •protected internal
  • 6.
    Classes and Objects MyClassmyObject_One=new MyClass(); MyClass myObject_Two=new MyClass(); Or var myObject_One=new MyClass(); var myObject_Two=new MyClass();
  • 7.
    Functions <access_modifier> <return_type> Functions(<Parameters>) { //Function Logic codes here } • return_type is void => write return; or don’t write anything • return_type is other than void => return object of the return_type • Parameters can be of any number • Function Overloading (inside the same class with same name but different signature): • Add(int a, int b) => a + b; • Add(int a, int b, int c) =>a + b + c;
  • 8.
    Constructors • a specialmethod that is used to initialize a newly created object and is called just after the memory is allocated for the object. public class ClassName { private int _number; public ClassName() //parameterless constructor { _number=10; } public ClassName(int number) //parameterized constructor{ _number=number; } } ClassName myObject_One=new MyClass(); //the variable number has the value 10 ClassName myObject_Two=new MyClass(2); //the variable number has the value 2
  • 9.
    Destructors ~ClassName() { } • Destructorsare invoked automatically, and cannot be invoked explicitly. • Destructors cannot be overloaded.Thus, a class can have, at most, one destructor. • Destructors are not inherited.Thus, a class has no destructors other than the one, which may be declared in it. • Destructors cannot be used with structs.They are only used with classes. • An instance becomes eligible for destruction when it is no longer possible for any code to use the instance. • Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction. • When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.
  • 10.
    Data Members • Constantsrepresenting constant values • Fields representing variables • Properties that define the class features and include actions to fetch and modify them • Events generated to communicate between different classes /objects • Indexers that help in accessing class instances similar to arrays • Operators that define semantics when used in expressions with class instances • Static constructor to initialize the class itself • Types that are local to the class (nested type)
  • 11.
  • 12.
    Encapsulation • Encapsulation isthe process of hiding irrelevant data from the user. • These are the irrelevant information for the mobile user, that’s why it is encapsulated inside a cabinet. • To understand encapsulation, consider an example of a 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 the analog signal and vice versa.
  • 13.
    Encapsulation public class Rectangle { privatefloat _length; private float _breadth; public float Area { get{return _length * _breadth;} } public float Perimeter { get{return 2*(_length + _breadth);} } } • The Encapsulation fields of a class basically can be write-only or can be read-only. • A Encapsulated class can have control over in its fields. • A class can change data type of its fields anytime but users of this class do not need to change any code.
  • 14.
    Abstraction • Abstraction isjust opposite of Encapsulation. • Abstraction is a mechanism to show only relevant data to the user. • It is an abstraction because you are seeing only relevant information instead of their internal engineering. • Consider the same mobile example again. Whenever you buy a mobile phone, you see their different types of functionalities as a camera, mp3 player, calling function, recording function, multimedia etc.
  • 15.
    Abstraction public abstract classShape { private float _area; private float _perimeter; public float Area { get{return _area;} set{_area = value;} } public float Perimeter { get{return _perimeter;} set{_perimeter = value;} } public abstract void CalculateArea(); public abstract void CalculatePerimeter(); }
  • 16.
    Inheritance • Allows usto define a class in terms of another class, which makes it easier to create and maintain an application. • Provides an opportunity to reuse the code functionality and speeds up implementation time. • inherit data and functions from multiple base classes or interfaces. • Classes in Inheritance • Base Class :The Origin Classes • Derived Classes : Derived from base class • Sealed Classes :This classes are the last of their kind. Cannot derived further
  • 17.
    Inheritance • Example : •class A is the origin class having the public member One, protected memberTwo and private memberThree • class B : A this means B is derived from A having public member Four • class C : B this means C is derived from B • sealed class D : A Now D is derived from A and D is last of its species. • In this example, when we create an instance of C “Obj_c”, the constructor of hierarchy A is called first, then B and then C. • public members are accessible from the object of C, i.e. Member One can be accessible. We can use Obj_c.One • Protected members are public inside the class C but not accessible outside the Object of C. i.e. we can useTwo Inside the Class C but Obj_c.Two is not accessible • private members are private only inside the class and cannot be used outside any classes. We cannot use memberThree not Obj_c.Three is notValid.
  • 18.
    Inheritance //Base class orParent class. public class Shape { public Shape(double Length , double Breadth) { this.Length=Length; this.Breadth=Breadth } protected double Length; protected double Breadth; public void ShowDim() { Console.WriteLine(“Length and Breadth” + Length + " and " + Breadth); } } //Derived class or Child class. public class Rectangle : Shape { public Rectangle (double Length , double Breadth) : base( Length , Breadth) { } public double Area() { return Length * Breadth; } public double Perimeter() { return 2* ( Length + Breadth ); } }
  • 19.
    Polymorphism • Polymorphism refersto the ability to present the same interface for different forms. • Polymorphism is often expressed as 'one interface, multiple functions’. • Polymorphism can be static or dynamic. • Static : the response to a function is determined at the compile time. • Dynamic : it is decided at run-time. • Static Polymorphism • Function overloading • Operator overloading • Dynamic polymorphism is implemented by abstract classes and virtual functions.
  • 20.
    Polymorphism • Dynamic polymorphismis implemented by abstract classes and virtual functions. • When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual/abstract functions. • The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime. • The derived class needs to be overridden in case of any changes to be done from base classes.
  • 21.
    Polymorphism abstract class Shape{ public abstract int area(); } --OR-- public class Shape { public virtual int area() { return 0; } } public class Rectangle: Shape { private int length; private int width; public Rectangle( int a = 0, int b = 0) { length = a; width = b; } public override int area () { Console.WriteLine("Rectangle class area :"); return (width * length); } }
  • 22.
    Interface And AbstractClasses Interface Abstract Class Supports multiple inheritance Does not support multiple inheritance Does not contain data members Contains data members No Constructors Contains constructors Contains only signature of members Contains both complete and incomplete members Cannot have access modifiers (all assumed public) Can have access modifiers for the functions, members Members cannot be static Only complete members can be static
  • 23.
    Interface • An interfaceis a contract • An interface is an empty shell • Implementing an interface consumes very little CPU // A motor vehicles should look like this: interface MotorVehicle { void run(); int getFuel(); }
  • 24.
    Abstract Class • Abstractclasses, unlike interfaces, are classes • More expensive to use, because there is a look-up to do when you inherit from them. • You can define a behavior for them. abstract class MotorVehicle{ int fuel; int getFuel() => fuel; abstract void run(); }
  • 25.
    Extending a Class •Extension methods enable you to "add" methods to existing types without creating a new derived type. • Extension methods are a special kind of static method. • They are called as if they were instance methods on the extended type. • Define a static class to contain the extension method. • Implement the extension method as a static method with at least the same visibility as the containing class. • The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier. • Call the methods as if they were instance methods on the type.
  • 26.
    Extending a Class publicstatic class MyExtensions { public static int WordCount(this String str,<parameters>){ return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } } string s = "Hello WebinarforallNepal"; int i = s.WordCount(<parameters>);
  • 27.

Editor's Notes

  • #24 An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way". An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.
  • #25 It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!".