How to override methods in C#

Virtual and override member function


class Class1//from   w  w w  .  ja v a  2  s .com
{
    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;// ww w .j  a v a 2  s .c  o 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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor