Monday, June 22, 2009

Abstract in C#

The abstract modifier can be used with classes, methods, properties, indexers, and events.

CLASS

Abstract modifier in a class declaration indicates that the class is intended only to be a base class of other classes. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

-> An abstract class can contain either abstract methods or non abstract methods. An abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members.
-> An abstract class cannot be instantiated.
-> An abstract class cannot be a sealed class.
-> A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
-> An abstract class must provide implementation for all interface members. An abstract class that implements an interface might map the interface methods onto abstract methods.
-> 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.

Example:

abstract class MyBaseClass // Abstract class
{
protected int x = 100;
protected int y = 150;
public abstract void MyMethod(); // Abstract method

public abstract int GetX // Abstract property
{
get;
}

public abstract int GetY // Abstract property
{
get;
}
}

class MyDerivedC: MyBaseClass
{
public override void MyMethod()
{
x++;
y++;
}

public override int GetX // overriding property
{
get
{
return x+10;
}
}

public override int GetY // overriding property
{
get
{
return y+10;
}
}

public static void Main()
{
MyDerivedClass mC = new MyDerivedClass();
mC.MyMethod();
Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY);
}
}

METHODS

-> Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
-> An abstract method is implicitly a virtual method.
-> Abstract method declarations are only permitted in abstract classes.
-> Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example: public abstract void MyMethod();
-> The implementation is provided by an overriding method, which is a member of a non-abstract class.
-> It is an error to use the static or virtual modifiers in an abstract method declaration.


PROPERTY

Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.

-> It is an error to use the abstract modifier on a static property.
-> An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

0 comments: