Académique Documents
Professionnel Documents
Culture Documents
OOPS or Object Oriented Programming Concepts but some of the concepts have been
always used in one or the other programming languages. For example you must have used
structs in C which is a good example of encapsulation. There are four major pillar of OOPS.
Let’s try to understand each one of them by taking some examples also:-
1.) Encapsulation
2.) Abstraction
3.) Polymorphism
4.) Inheritance
Encapsulation:-
Interview Definition:- Binding data and member functions together inside a single unit.
How to Encapsulate:- By creating types e.g Classes and Struct
Bu using encapsulation we can create out own custom types by reusing the existing or
primitive types.
Abstraction:-
Abstraction defines way to abstract or hide your data and members from outside world.
Simply speaking Abstraction is hiding the complexities of your class or struct or in a generic
term Type from outer world. This is achieved by means of access specifiers.
Interview Definition: - Hiding the complexities of your type from outside world.
How to Abstract: - By using Access Specifiers
.Net has five access specifiers:-
Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member
functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes
outside the assembly through member functions.
Let’s try to understand by a practical example:-
Interview Tip:-
The default access specifier for a class in internal. Mind it I mean class not class’s data
members.
Now lets try to copy the same code inside Main method and try to compile
[STAThread]
static void Main()
{
//Access specifiers comes into picture only when you create object of class outside
the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access private data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data through object.
obj.m=10;
obj.n=10;
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
What if Main is inside another assembly
[STAThread]
static void Main()
{
//Access specifiers comes into picture only when you create object of class outside
the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access private data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data through object.
// obj.m=10; // Error can’t access internal data outside assembly
// obj.n=10; // Error can’t access internal data outside assembly
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
There are two more scenerios for internal data members that we will discuss after
inheritance also protected data member will be more clear once we have some idea about
inheritance model.In the next article we will be discussing Polymorphism and Inheritance in
depth.
Inheritance:-
Method Overriding :
-There is only a practical difference between hiding and overriding except from the fact that
hiding use new keyword whereas Overriding uses override keywird and the overriden
function must be declared as either virtual or abstract on the base class.One more thing is
that you can also hide data members but can override only member functions.
So I think the ingredients are ready to start creating our recipe.Lets start cooking.
Scenerio 1 :-
What dats ia avilable through inheritance:-
Scenerio 1 :-
Class2 is within same assembly
Now lets create objects of base and child and see the behavior:-
Class2 obj = new Class2();
obj.j = 10; // Data was public so can be inherited.Access through member function as well
as object of child
obj.k=10; // Compilation Error. Data was protected so can be inherited.Access through
member function only
obj.m = 10; // Data was internal so can be inherited.Access through member function as
well as object of child
obj.n = 10; // Data was protected internal so can be inherited.Access through member
function as well as object of child
Scenerio 3:-
We will create objects of base and child normally and through casting in all following
samples:-
MyClass obj = new MyClass();
MyChild obj2 = new MyChild();
MyClass objCastedFromChild = (MyClass)obj2;
obj.foo();
obj2.foo();
objCastedFromChild.foo();
output:-
Base version of foo
Base version of foo
Base version of foo
Members are searched from child to base when there is no implementation in child it is first
searched in immediate base and so on till it’s found or a compilation error comes.Since
there is no function in child with name foo all the three objects will call base version of foo.
We will continue our discussion in the next article so that you can grasp the concepts slowly
and steadily.Please try to imlement everything on your own to have a good command over
OOPS.
Continuing our discussion on .Net.This is the third article in the series and in this we will be
discussing all the possible scenerio's of inheritance.
Scenario 4:-
Function present in both base class and child class. This concept is called Method hiding.
See the sample code below:
Without new keyword compiler will give a warning that you are hiding the base class
implementation. We will create objects of base and child normally and through casting in all
following samples:-
output:-
Base version of foo
Child version of foo
Base version of foo
So in normal scenerio’s follow the simple rule. Thy object thy function.
Scenerio 5:-
Function present in both base class and child class but this time virtual in base class. See
the sample code below:
Without new keyword compiler will give a warning that you are hiding the base class
implementation. We will create objects of base and child normally and through casting in all
following samples:-
output:-
Base version of foo
Child version of foo
Base version of foo
So in this scenerio also follow the simple rule. Thy object thy function.
Scenerio 6:-
Function present in base class as virtual but not present in child class. See the sample code
below:
}
We will create objects of base and child normally and through casting in all following
samples:-
output:-
Base version of foo
Base version of foo
Base version of foo
So no difference from scenerio 3. Members are searched from child to base when there is no
implementation in child it is first searched in immediate base and so on till it’s found or a
compilation error comes.Since there is no function in child with name foo all the three
objects will call base version of foo.
Scenerio 7:-
Function declared as virtual in base class and overridden in child class. See the sample code
below:
We will create objects of base and child normally and through casting in all following
samples:-
So you can see the difference. In Method Hiding base class object was calling its own
implementation but in this case base is calling the child class’s implementation. So in case
of overriding and casting behavior changes.
Scenerio 8:-
Function declared as abstract in base class and overridden in child class. See the sample
code below:
Now we can’t create base class object directly as base class is now an abstract class nad
thus objects can now be creates via casting only. We will create objects of child normally
and base object through casting in following sample:-
output:-
Child version of foo
Child version of foo
So you can see the difference. In Method Hiding base class object was calling its own
implementation but in this case base is calling the child class’s implementation. So in case
of overriding and casting behavior changes.
Operator Overloading in C#
Simply, Making an operator like (+) or (-) etc.. do a special job in your class. In our Tutorial
it will be Add (+), Subtract(-) and Multiply (*) tow Complex numbers.
In Complex numbers addition, we add the real parts alone, and the imaginary parts alone as
well, means if we have a class like this:
public ComplexNumber()
{
}
Then what will be the the implementation of the Operator (+) to be overloaded??
Subtract will be the same as Adding to Complex numbers, just we'l have to Change the
Operator, but Multiplication has another way of calculation :
Operator overloading makes a program clearer than accomplishing the same operations
with explicit method calls. Now if you want to add tow complex numbers of Type
ComplexNumber you just need to instaniate tow objects from it then do this:
but if you don't have the operator overload for + operator what you should do to add
them??
repeat the implementation of the + operator several times, or put it in a method and call it
several times.
In this article I will try to explain sealed class and sealed method in a very simple way.
Sealed Class
The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed
class is specified as the base class of another class.
1. A class, which restricts inheritance for security reason is declared, sealed class.
2. Sealed class is the last class in the hierarchy.
3. Sealed class can be a derived class but can't be a base class.
4. A sealed class cannot also be an abstract class. Because abstract class has to provide
functionality and here we are
restricting it to inherit.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sealed_class
class Program
obj.Display();
Console.ReadLine();
Sealed Methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sealed_method
class Program
Console.WriteLine("Virtual method");
}
// Now the display method have been sealed and can;t be overridden
Console.WriteLine("Sealed method");
//{
// {
// }
//}
ob1.Display();
Console.ReadLine();
Hope this article will give you better view of sealed class and sealed method. Waiting! for
your valuable feedback.
Introduction
Partial classes and partial methods are two programming language features of .NET
programming languages that make it possible for developers to extend and enhance auto-
generated code. In a nutshell, partial classes allow for a single class's members to be
divided among multiple source code files. At compile-time these multiple files get combined
into a single class as if the class's members had all been specified in a single file. Partial
methods are methods defined in a partial class that are (optionally) divided across two files.
With partial methods one file contains the method signature - the method name, its return
type, and its input parameters - while the body is (optionally) defined in a separate file. If
the partial method's body is not defined then the compiler automatically removes the partial
method signature and all calls to the method at compile-time.
Partial classes and partial methods are most commonly used in auto-generated code. The
framework or tool that is auto-generating the code can create the auto-generated classes as
partial classes. If the developer using the auto-generated code wants to extend the
functionality of the class by adding new methods or properties she can do so by creating a
new partial class file and putting her additions there. By having these additions in a
separate file there's no risk of the tool overwriting the developer's changes when
regenerating the code.
Regardless of whether you know the ins and outs of partial classes you use them every time
you create an ASP.NET web page using a code-behind class. And if you routinely use auto-
generated libraries, like LINQ to SQL or Typed DataSets, then it behooves you to be familiar
with both partial classes and partial methods, as they offer opportunities for safely
extending the functionality of auto-generated code. Read on to learn more about how these
features work and how you can put them to work.
...
}
With partial classes you can divide the members across separate files. A class is identified
as being a partial class via the partial keyword (or Partial in VB), as the following code
snippet illustrates:
...
}
The last use of partial classes is the most important one of the three and is one ASP.NET
developers enjoy every single time we create an ASP.NET page that uses a code-behind
class.
The markup file contains static HTML. Web controls, and data-binding syntax. The code file
contains page-level event handlers and event handlers for the Web controls defined in the
markup page. Moreover, the code file can reference the Web controls defined in the markup
file. This begs the question - how does the code file have access to the Web controls defined
in the markup file?
If you look at the class definition in the code file you'll note that the class is marked as a
partial class. Here's an example:
This code defines a partial class named _Default (or whatever the name of the page
happens to be). Note that it does not contain any references to the Web controls defined in
the markup portion. That is, if we had a Label Web control in the markup file with its ID
property set to lblMessage we could write code in the code-behind class like lblMessage.Text
= "Hello, World!" Yet there is no definition for the lblMessage Label in the code-behind class.
The Web controls defined in the markup portion are implemented as properties in an auto-
generated partial class. If you are using a web application
Project you can browse to this partial class directly by visiting the
WebPageName.designer.cs or WebPageName.designer.vb file; in a web site
Project this designer partial class file is created behind the scenes. The following code shows
an example of such a designer partial class:
/// <summary>
/// lblMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblMessage;
}
The _Default class is split across two files: the auto-generated designer file and your code-
behind class file. The code-behind class file can access the Web controls defined in the
markup file because they are actually implemented as properties in the class itself, albeit in
a separate, auto-generated file.
If you developed ASP.NET 1.x applications then you likely remember what life
was like before partial classes. Without partial classes, Visual Studio had to
embed the Web control property declarations directly in the code-behind class.
This resulted in a hidden region within each code-behind class that defined these
properties. With partial classes this low-level scaffolding is placed in a separate
file, keeping our code-behind class tidier, more readable, and more maintainable.
Partial classes are also useful with tools like Typed DataSets and LINQ to SQL, which auto-
generate class files to assist with data access. It's not uncommon that you need to add
additional properties or methods. Doing so involves creating a partial class and adding the
needed methods or properties in that separate file.
Returning to our Employee example, with partial methods we could define a partial method
named
...
}
}
Note that in the first file, Employee.cs, the method ApplyAnnualCostOfLivingRaise is defined
as a partial method. No body is supplied, yet the method can be called from other methods
in the class, as it is from PerformEndOfYearProcesses. Keep in mind that the partial
method's body is optional. If the body is not supplied then when the class is compiled all
references to the method ApplyAnnualCostOfLivingRaise are removed. If the body is
defined, as it is in the EmployeeAnnualCostOfLivingRaise.cs file, then the compiler treats the
method as if it had been defined in the same class file.
Partial methods are especially useful in auto-generated code situations. A code generating
tool might now that there are certain extension points that some users are going to be
interested in customizing. For example, the objects created in LINQ to SQL have partial
methods like OnLoaded, OnCreated, OnPropertyNameChanging, and
OnPropertyNameChanged. The auto-generated code calls the OnCreated partial method
from its constructor. If you want to run custom code when one of these objects is created
you can create a partial class and define the body for the OnCreated partial method. (If you
do not need to add such customization then all calls to the OnCreated method are removed
at compile-time.)
Conclusion
Partial classes and partial methods are language features available in C# and Visual Basic
that, among other uses, provide a simple and safe way to add new functionality or extend
existing functionality of auto-generated code. In short, partial classes and partial methods
allow class and method definitions to be split across multiple files, which allows the code
generator tool to make its writes to one file while your customizations can be made to an
entirely separate file. The compiler intelligently combines the definitions together into a
single class at compile-time.