Object Oriented Concepts of C#  

About myself
My Technical Skills
Software Life Cycle
C# OOP Concepts
SQLServer Resources
ASP.Net  Resources
DotNet 2.0 New  Features
DotNet 3.0 New Features
Contact Information
 


Abstraction—Abstraction manages the complexities of a business problem by allowing you to identify a set of objects involved with that business problem.


Encapsulation—Encapsulation hides the internal implementation of an abstraction within the particular object.


Polymorphism—Polymorphism provides for multiple implementations of the same method. For example, different objects can have a Save method, each of which perform different processing.
using System;
namespace OOP
{
public class Aperture
{
public Aperture()
{
}
protected double height;
protected double width;
protected double thickness;
public double GetVolume()
{
double volume = height*width*thickness;
if(volume<0)
return 0;
return volume;
}
public virtual void Out()
{
Console.WriteLine("Aperture virtual method called");
}
}

public class Door : Aperture
{
public Door() : base()
{

}

public override void Out()
{
Console.WriteLine("Door virtual method called");
}
public bool isOutside = true;
}

class TestApp
{
///


/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
Aperture ap = new Door();
ap.GetVolume();

ap.Out();
}
}
}


Inheritance—The excitement of Visual Basic .NET lies in inheritance. Visual Basic 5 introduced the concept of interface inheritance, which allows you to reuse the interface of a class, but not its implementation. Visual Basic .NET provides for true implementation inheritance whereby you can reuse the implementation of a class.

Abstract ClassAbstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.
An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
An example of an abstract class declaration is:
abstract class absClass
{
}
An abstract class can contain either abstract methods or non-abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
An example of an abstract method:
abstract class absClass
{
public abstract void abstractMethod();
}
Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non-abstract members. For example:
abstract class absClass
{
public void NonAbstractMethod()
{
Console.WriteLine("NonAbstract Method");
}
}
A sample program that explains abstract classes:
using System;

namespace abstractSample
{
//Creating an Abstract Class
abstract class absClass
{
//A Non abstract method
public int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}

//An abstract method, to be
//overridden in derived class
public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//A Child Class of absClass
class absDerived:absClass
{
[STAThread]
static void Main(string[] args)
{
//You can create an
//instance of the derived class

absDerived calculate = new absDerived();
int added = calculate.AddTwoNumbers(10,20);
int multiplied = calculate.MultiplyTwoNumbers(10,20);
Console.WriteLine("Added : {0},
Multiplied : {1}", added, multiplied);
}

//using override keyword,
//implementing the abstract method
//MultiplyTwoNumbers
public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1 * Num2;
}
}
}
In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation.
The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class.
Example
//Abstract Class1
abstract class absClass1
{
public abstract int AddTwoNumbers(int Num1, int Num2);
public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2
abstract class absClass2:absClass1
{
//Implementing AddTwoNumbers
public override int AddTwoNumbers(int Num1, int Num2)
{
return Num1+Num2;
}
}

//Derived class from absClass2
class absDerived:absClass2
{
//Implementing MultiplyTwoNumbers
public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1*Num2;
}
}
In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived from absClass2 and the MultiplyTwoNumbers is implemented there.
Abstract properties
Following is an example of implementing abstract properties in a class.
//Abstract Class with abstract properties
abstract class absClass
{
protected int myNumber;
public abstract int numbers
{
get;
set;
}
}

class absDerived:absClass
{
//Implementing abstract properties
public override int numbers
{
get
{
return myNumber;
}
set
{
myNumber = value;
}
}
}
In the above example, there is a protected member declared in the abstract class. The get/set property for the member variable myNumber is defined in the derived class absDerived.
Important rules applied to abstract classes
An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.
//Incorrect
abstract sealed class absClass
{
}
Declarations of abstract methods are only allowed in abstract classes.
An abstract method cannot be private.
//Incorrect
private abstract int MultiplyTwoNumbers();
The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
An abstract method cannot have the modifier virtual.
Because an abstract method is implicitly virtual.
//Incorrect
public abstract virtual int MultiplyTwoNumbers();
An abstract member cannot be static.
//Incorrect
publpublic abstract static int MultiplyTwoNumbers();
Abstract class vs. Interface
An abstract class can have abstract members as well non-abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
An example of interface:
interface iSampleInterface
{
//All methods are automaticall abstract
int AddNumbers(int Num1, int Num2);
int MultiplyNumbers(int Num1, int Num2);
}
Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.
A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.
The selection of interface or abstract class depends on the need and design of your project. You can make an abstract class, interface or combination of both depending on your needs

Delegate
A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure.

This declaration takes the following form::

[attributes] [modifiers] delegate result-type identifier ([formal-parameters]);

where:
attributes (Optional)
Additional declarative information. For more information on attributes and attribute classes, see 17. Attributes.
modifiers (Optional)
The allowed modifiers are new and the four access modifiers.
result-type
The result type, which matches the return type of the method.
identifier
The delegate name.
formal-parameters (Optional)
Parameter list. If a parameter is a pointer, the delegate must be declared with the unsafe modifier.

Remarks
A delegate lets you pass a function as a parameter. The type safety of delegates requires the function you pass as a delegate to have the same signature as the delegate declaration. See the Delegates Tutorial for more information on using delegates.

The Delegates Tutorial shows how to compose delegates, that is, create delegates from other delegates. A delegate that contains an out parameter cannot be composed.

Delegates are the basis for events.


Example 1
The following is a simple example of declaring and using a delegate.
// keyword_delegate.cs
// delegate declaration
delegate void MyDelegate(int i);

class Program
{
public static void Main()
{
TakesADelegate(new MyDelegate(DelegateFunction));
}

public static void TakesADelegate(MyDelegate SomeFunction)
{
SomeFunction(21);
}

public static void DelegateFunction(int i)
{
System.Console.WriteLine("Called by delegate with number: {0}.", i);
}
}

Output
Called by delegate with number: 21.

Example 2
In the following example, one delegate is mapped to both static and instance methods and returns specific information from each.

// keyword_delegate2.cs
// Calling both static and instance methods from delegates

using System;

// delegate declaration
delegate void MyDelegate();

public class MyClass
{
public void InstanceMethod()
{
Console.WriteLine("A message from the instance method.");
}

static public void StaticMethod()
{
Console.WriteLine("A message from the static method.");
}
}

public class MainClass
{
static public void Main()
{
MyClass p = new MyClass();

// Map the delegate to the instance method:
MyDelegate d = new MyDelegate(p.InstanceMethod);
d();

// Map to the static method:
d = new MyDelegate(MyClass.StaticMethod);
d();
}
}

Output
A message from the instance method.
A message from the static method.


Virtual keyword -The virtual keyword is used to modify a method or property declaration, in which case the method or the property is called a virtual member. The implementation of a virtual member can be changed by an overriding member in a derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
By default, methods are non-virtual. You cannot override a non-virtual method.
You cannot use the virtual modifier with the following modifiers:
static abstract override
Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.
• It is an error to use the virtual modifier on a static property.
• A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.


Override-Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
You cannot use the following modifiers to modify an override method:
new static virtual abstract
An overriding property declaration must specify the exact same access modifier, type, and name as the inherited property, and the overridden property must be virtual, abstract, or override.


Volatile

The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.
Remarks
The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment.
The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.
The type of a field marked as volatile is restricted to the following types:
Any reference type.
Any pointer type (in an unsafe context).
The types sbyte, byte, short, ushort, int, uint, char, float, bool.
An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint.
For more information on volatile, see 10.4.3 Volatile fields.
Example
The following sample shows how to declare a public field variable as volatile.
// csharp_volatile.cs
class Test
{
public volatile int i;

Test(int _i)
{
i = _i;
}
public static void Main()
{

}
}

Sealed
A sealed class cannot be inherited. It is an error to use a sealed class as a base class. Use the sealed modifier in a class declaration to prevent inheritance of the class.
It is not permitted to use the abstract modifier with a sealed class.
Structs are implicitly sealed; therefore, they cannot be inherited.
Example
// cs_sealed_keyword.cs
// Sealed classes
using System;
sealed class MyClass
{
public int x;
public int y;
}

class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Output
x = 110, y = 150


Copyright © 2005  Mayur Shrimali. All rights reserved.