Recent Posts

Posts RSS

Where to Use abstract key word in .net..?

Reactions: 

The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.




Abstract classes have the following features:
  §  An abstract class cannot be instantiated.
  §  An abstract class may contain abstract methods and accessors.
  §  It is not possible to modify an abstract class with the sealed (C# Reference) modifier, which means that the class cannot be inherited.
  §  A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
  §  An abstract method is implicitly a virtual method.
  §  Abstract method declarations are only permitted in abstract classes.
       §  The implementation is provided by an overriding method override (C# Reference), which is a member of a non-abstract class.
       §  The implementation is provided by an overriding method override (C# Reference), 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.
       §  It is an error to use the static or virtual modifiers in an abstract method declaration.




      Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation. Please check the following example. In this example, the class DerivedClass is derived from an abstract class BaseClass. The abstract class contains an abstract method, AbstractMethod, and two abstract properties, X and Y.

    // Abstract Classes
    using System;
    abstract class BaseClass   // Abstract class
    {
        protected int _x = 100;
        protected int _y = 150;
        public abstract void AbstractMethod();   // Abstract method
        public abstract int X { get; }
        public abstract int Y { get; }
    }
    class DerivedClass : BaseClass
    {
        public override void AbstractMethod()
        {
            _x++;
            _y++;
        }

        public override int X   // overriding property
        {
            get
            {
                return _x + 10;
            }
        }

        public override int Y   // overriding property
        {
            get
            {
                return _y + 10;
            }
        }

        static void Main()
        {
            DerivedClass o = new DerivedClass();
            o.AbstractMethod();
            Console.WriteLine("x = {0}, y = {1}", o.X, o.Y);
        }
    }
}





kick it on DotNetKicks.com

0 comments: