Sponsored Ad

Thursday, October 22, 2009

C# Override

When an instance method declaration includes an override modifier, the method is said to be a method of cancellation.
An override method overrides an inherited virtual method with the same signature. Whereas a virtual method declaration introduces a new method, an override method declaration specializes establishing a virtual method inherited by providing a new implementation of the method.
So, ultimately, higher in C # makes use of the override "keyword. To override a method means to replace it with a new form of data management.

For the purpose of locating the ring base method, a method that is considered accessible if it is public or if internal and declared in the same program as C.

Example:

namespace MethodOverriding

{

    class A

    {

        public virtual void Foo() { Console.WriteLine("A::Foo()"); }

    }

    class B : A

    {

        public override void Foo() { Console.WriteLine("B::Foo()"); }

    }

    class Program

    {

        static void Main(string[] args)

        {

            A a;

            B b;

            a = new A();

            b = new B();

            a.Foo();  // output --> "A::Foo()"

            b.Foo();  // output --> "B::Foo()"

            a = new B();

            a.Foo();  // output

            Console.ReadLine();

        }

    }

}

Few points to remember:

  • The base class method must be defined virtual
  • The method in the derived class must be preceded by new or override keywords
  • If the method in the derived class is preceded with the new keyword, the method is defined as independent of the method in the base class.
  • If the method in the derived class is preceded by the override keyword, the objects of the derived class will call that method rather than the base class method.
  • The base class method can be called from within the derived class using base keyword.
  • The replacement, virtual, and new keywords can also be applied to properties, indexers, and events.

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers