Vous êtes sur la page 1sur 21

Introduction

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.

public class Class1


{
int i; //No Access specifier means private
public int j; // Public
protected int k; //Protected data
internal int m; // Internal means visible inside assembly
protected internal int n; //inside assembly as well as to derived classes
outside assembly
static int x; // This is also private
public static int y; //Static means shared across objects
[DllImport("MyDll.dll")]
public static extern int MyFoo(); //extern means declared in this assembly
defined in some other assembly
public void myFoo2()
{
//Within a class if you create an object of same class then you can access all data
members through object reference even private data too
Class1 obj = new Class1();
obj.i =10; //Error can’t access private data through object.But here it is
accessible.:)
obj.j =10;
obj.k=10;
obj.m=10;
obj.n=10;
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10;
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
}

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:-

Inheritance basically provides two models. Reusability model and extensibility


model.Reusability model was there in C also thorugh header file and in VB since Visual Basic
is an object based language. An object based language is the one where in we can use the
objects or components or modules as is but can’t modify or extend their behavior.
Interview Definition: - Extending or enhancing the functionality of base class.
In inheritance few terms or concepts which are hiding and overriding.
Method or Data Hiding:- Having data member or function in child class having same
signature as that in base class. This is not an error but compiler shows you a warning
messages when you have same data member in both child and base stating that you are
hiding the base class implentation if hiding is intended use new keyword.So by specifying
new keyword with data member and functions you can hide base class’s implementation of
data or function.This will be more clear with an example later on.

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:-

public class Class1


{
int i; //No Access specifier means private
public int j; // Public
protected int k; //Protected data
internal int m; // Internal means visible inside assembly
protected internal int n; //inside assembly as well as to derived classes
outside assembly
static int x; // This is also private
public static int y; //Static means shared across objects
[DllImport("MyDll.dll")]
public static extern int MyFoo(); //extern means declared in this assembly
defined in some other assembly
public void myFoo2()
{
//Within a class if you create an object of same class then you can access all data
members through object reference even private data too
Class1 obj = new Class1();
obj.i = 10; //Error can’t access private data through object.
obj.j = 10;
obj.k = 10;
obj.m = 10;
obj.n = 10;
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10;
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
}

Scenerio 1 :-
Class2 is within same assembly

public class Class2:Class1


{
int publicDataFromBase, protectedDataFromBase, internalDataFromBase,
protectedInternalDataFromBase;
public void foo()
{
publicDataFromBase = j; // Data was public so can be inherited.Access through
member function as well as object of child
protectedDataFromBase = k; // Data was protected so can be inherited.Access
through member function only
internalDataFromBase = m; // Data was internal so can be inherited.Access
through member function as well as object of child
protectedInternalDataFromBase = n; // Data was protected internal so can be
inherited.Access through member function as well as object of child
y = 10; //Static data can be inherited.Data was public so can be
inherited.Access through member function as well as object of child
}
}

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

obj.foo(); //foo of child


obj.myFoo2(); //myFoo2 of base
Scenerio 2 :-
Class2 is in some other assembly

Class2 obj = new Class2();


obj.j = 10;
// obj.m = 10; //internal means public inside assembly but outside assmebly not visible
// obj.n = 10; // Protected internal means public inside assembly but outside assmebly
visible to derived classes through member functions
obj.foo();
obj.myFoo2();

Scenerio 3:-

Function present in base class not present in child class.


public class MyClass
{
public void foo()
{
Console.WriteLine(“Base version of foo”);
}
}

public class MyChild : MyClass


{

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.

For previous articles please refer:


http://www.dotnetspider.com/resources/18616-OOPS-Concepts-Net-Shake-your.aspx and
http://www.dotnetspider.com/resources/18617-OOPS-Concepts-Net-Shake-your.aspx

Scenario 4:-
Function present in both base class and child class. This concept is called Method hiding.
See the sample code below:

public class MyClass


{
public void foo()
{
Console.WriteLine("Base version of foo");
}
}

public class MyChild : MyClass


{
public new void foo()
{
Console.WriteLine("Child version of foo");
}
}

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:-

MyClass obj = new MyClass();


MyChild obj2 = new MyChild();
MyClass objCastedFromChild = (MyClass)obj2;
obj.foo();
obj2.foo();
objCastedFromChild.foo();

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:

public class MyClass


{
public virtual void foo()
{
Console.WriteLine("Base version of foo");
}
}

public class MyChild : MyClass


{
public new void foo()
{
Console.WriteLine("Child version of foo");
}
}

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:-

MyClass obj = new MyClass();


MyChild obj2 = new MyChild();
MyClass objCastedFromChild = (MyClass)obj2;
obj.foo();
obj2.foo();
objCastedFromChild.foo();

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:

public class MyClass


{
public virtual void foo()
{
Console.WriteLine(“Base version of foo”);
}
}

public class MyChild : MyClass


{

}
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

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:

public class MyClass


{
public virtual void foo()
{
Console.WriteLine(“Base version of foo”);
}
}

public class MyChild : MyClass


{
public override void foo()
{
Console.WriteLine(“Child version of foo”);
}

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
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.

Scenerio 8:-
Function declared as abstract in base class and overridden in child class. See the sample
code below:

public abstract class MyClass


{
public abstract void foo();

public class MyChild : MyClass


{
public override void foo()
{
Console.WriteLine(“Child version of foo”);
}

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:-

//MyClass obj = new MyClass(); //Not possible now


MyChild obj2 = new MyChild();
MyClass objCastedFromChild = (MyClass)obj2;
obj2.foo();
objCastedFromChild.foo();

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#

What is Operator Overloading?

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.

Declearing Oparetor overloading

public static returnType operator +(ParamList,....,....)


{
//Implementation pf your operator
}

Add 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 class ComplexNumber


{
private int intReal;
private int intImaginary;

public ComplexNumber()
{
}

public ComplexNumber(int a, int b)


{
Real = a;
Imaginary = b;
}

public int Real


{
get
{
return intReal;
}
set
{
intReal = value;
}
}

public int Imaginary


{
get
{
return intImaginary;
}
set
{
intImaginary = value;
}
}

Then what will be the the implementation of the Operator (+) to be overloaded??

it will be like this:

public static ComplexNumber operator +(ComplexNumber x, ComplexNumber y)


{
//Adding Real Parts then & adding Imaginary Parts and return
//the result in a type of ComplexNumber
//Real Part = x.Real + y.Real
//Imaginary Part = x.Imaginary + y.Imaginary
return new ComplexNumber(x.Real + y.Real, x.Imaginary + y.Imaginary);
}

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 :

public static ComplexNumber operator *(ComplexNumber x, ComplexNumber y)


{
//Real Part = (x.Real * y.Real) - (x.Imaginary * y.Imaginary)
//Imaginary Part = (x.Real * y.intImaginary) + (y.Real * x.intImaginary)
return new ComplexNumber(x.Real * y.Real - x.Imaginary * y.Imaginary,
x.Real * y.intImaginary + y.Real * x.intImaginary);
}

Why use Operator Overloading?

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:

z = x + y; //x, y & z are ComplexNumber

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.

ComplexNumber fromating as string


Just need to override ToString() method like this:

public override string ToString()


{
//if (intImaginary < 0) then print the Imaginary part as
// ("-" intImaginary * -1 "i") like this 1-5i
//else print it as ("+" intImaginary "i") like this 1+5i

return "(" + intReal + (intImaginary < 0 ? " - " +


(intImaginary * -1) : " + " + intImaginary) + "i )";
}

for the complete code check the attached project.

What is sealed class and sealed method?

In this article I will try to explain sealed class and sealed method in a very simple way.

Sealed Class

Sealed class is used to define the inheritance level of a 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.

Some points to remember:

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.

Practical demonstration of sealed class

using System;
using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace sealed_class

class Program

public sealed class BaseClass

public void Display()

Console.WriteLine("This is a sealed class which can;t be further inherited");

public class Derived : BaseClass

// this Derived class can;t inherit BaseClass because it is sealed

static void Main(string[] args)

BaseClass obj = new BaseClass();

obj.Display();
Console.ReadLine();

Sealed Methods

Sealed method is used to define the overriding level of a virtual method.

Sealed keyword is always used with override keyword.

Practical demonstration of sealed method

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace sealed_method

class Program

public class BaseClass

public virtual void Display()

Console.WriteLine("Virtual method");
}

public class DerivedClass : BaseClass

// Now the display method have been sealed and can;t be overridden

public override sealed void Display()

Console.WriteLine("Sealed method");

//public class ThirdClass : DerivedClass

//{

// public override void Display()

// {

// Console.WriteLine("Here we try again to override display method which is not


possible and will give error");

// }

//}

static void Main(string[] args)

DerivedClass ob1 = new DerivedClass();

ob1.Display();
Console.ReadLine();

Hope this article will give you better view of sealed class and sealed method. Waiting! for
your valuable feedback.

An Overview of Partial Classes and Partial Methods

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.

Splitting a Class Across Multiple Files


Partial classes allow a class's members - its methods, properties, and events - to be split
across multiple files; they were introduced as language features to C# 2.0 and Visual Basic
8.0, which were the versions of the languages that shipped with the .NET Framework 2.0 in
2005.. Prior to partial classes a class would need to be entirely defined within one file, like
so:

public class Employee


{
public int EmployeeID;
public string FirstName;
public string LastName;
public decimal Salary;

public void ApplyAnnualCostOfLivingRaise()


{
Salary *= 1.05M;
}

...
}

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:

// This portion of the partial class is defined in EmployeeProperties.cs


public partial class Employee
{
public int EmployeeID;
public string FirstName;
public string LastName;
public decimal Salary;
}

// This portion of the partial class is defined in EmployeeMethods.cs


public partial class Employee
{
public void ApplyAnnualCostOfLivingRaise()
{
Salary *= 1.05M;
}

...
}

Uses of Partial Classes


Partial classes have a variety of uses:

• They can be used to improve the readability of extremely large classes by


partitioning related methods into separate files. (Of course, if your project has very
large classes with thousands of lines of code you may want to consider refactoring
that massive class into several smaller classes.)
• For shops using source code control with exclusive checkouts dividing a class into
separate files can reduce the likelihood of one developer being blocked from working
on a class until it is checked in by another developer. And even when using non-
exclusive checkouts - which is usually the preferred method - having a class spread
across multiple files reduces merges.
• Partial classes enable the code generator to generate code in one file while the
developer who may need to extend the auto-generated logic can do so in a separate
file, which eliminates the worry that the code generator might overwrite a
developer's customizations.

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.

How Partial Classes Are Used In An ASP.NET Application


As you know, an ASP.NET page is typically divided into two files:

• A markup file with a .aspx extension, and


• A code file, with a .aspx.cs or .aspx.vb extension

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:

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
...
}
}

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:

public partial class _Default {

/// <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.

Life Before Partial Classes

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.

Defining a Method Across Two Files


Partial methods allow the definition of a method to be located in one file and the body of the
method to be optionally defined in another file. They can only be used in partial classes and
were introduced as language features in C# 3.0 and Visual Basic 9.0, the versions that
shipped with the .NET Framework 3.5 and Visual Studio 2008.

Returning to our Employee example, with partial methods we could define a partial method
named

// This portion of the partial class is defined in Employee.cs


public partial class Employee
{
public int EmployeeID;
public string FirstName;
public string LastName;
public decimal Salary;

public partial void ApplyAnnualCostOfLivingRaise();

public void PerformEndOfYearProcesses()


{
ApplyAnnualCostOfLivingRaise();

...
}
}

// This portion of the partial class is defined in EmployeeAnnualCostOfLivingRaise.cs


public partial class Employee
{
public partial void ApplyAnnualCostOfLivingRaise()
{
Salary *= 1.05M;
}
}

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.

Vous aimerez peut-être aussi