C# Override methods

In this chapter you will learn:

  1. Virtual and override member function
  2. new method not override

Virtual and override member function


class Class1/*from   w w  w . j av a 2  s.c  o  m*/
{
    public virtual void Hello()
    {
        System.Console.Write( "Hello from Class1" );
    }
}

class Class2 : Class1
{
    public override void Hello()
    {
        base.Hello();
        System.Console.Write( " and hello from Class2 too" );
    }

    public static void Main( string[] args )
    {
        Class2 c2 = new Class2();
        c2.Hello();
    }
}

The code above generates the following result.

new method not override


using System;//from  www .jav a  2  s .  co  m

class BaseClass
{
   virtual public void Print()
   { Console.WriteLine("This is the base class."); }
}

class DerivedClass : BaseClass
{
   override public void Print()
   { Console.WriteLine("This is the derived class."); }
}

class SecondDerived : DerivedClass
{
   new public void Print()
   {
      Console.WriteLine("This is the second derived class.");
   }
}

class MainClass
{
   static void Main()
   {
      SecondDerived derived = new SecondDerived();
      BaseClass mybc = (BaseClass)derived;
      derived.Print();
      mybc.Print();
   }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is member shadow
  2. When to use new and virtual in member shaow
Home »
  C# Tutorial »
    C# Types »
      C# Inheritance
C# Class Inheritance
C# base Keyword
C# seal Functions and Classes
C# Abstract Classes and Abstract Members
C# Polymorphism
C# Virtual Function Members
C# Override methods
C# Shadow inherited members
C# as operator
C# is operator