Demonstrates the use of a virtual property to override a base class property : Override Virtual « Class Interface « C# / C Sharp






Demonstrates the use of a virtual property to override a base class property

Demonstrates the use of a virtual property to override a base class property
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

//
// VProp.cs -- Demonstrates the use of a virtual method to override
//             a base class method.
//
//             Compile this program with the following command line:
//                 C:>csc VProp.cs
namespace nsVirtual
{
    using System;
    
    public class VPropclsMain
    {
        static public void Main ()
        {
            clsBase Base = new clsBase();
            clsFirst First = new clsFirst();
            Base.SetString ("This should set the base class property");
            First.SetString ("This should set the derived class property");
            Console.WriteLine();
            Console.WriteLine (Base.GetString());
            Console.WriteLine (First.GetString());
        }
    }
    class clsBase
    {
  public void SetString (string str)
        {
            StrProp = str;
        }
        public string GetString ()
        {
            return (StrProp);
        }
        virtual protected string StrProp
        {
            get
            {
                Console.WriteLine ("Getting Base string");
                return (m_BaseString);
            }
            set
            {
                Console.WriteLine ("Setting Base string");
                m_BaseString = value;
            }
        }
        private string m_BaseString = "";
    }
    class clsFirst : clsBase
    {
        override protected string StrProp
        {
            get
            {
                Console.WriteLine ("Getting derived string");
                return (m_DerivedString);
            }
            set
            {
                Console.WriteLine ("Setting derived string");
                m_DerivedString = value;
            }
        }
        private string m_DerivedString = "";
   }
}

           
       








Related examples in the same category

1.Polymorphism
2.Virtual keyword can be used to start a new inheritance ladder
3.Virtual and overloadVirtual and overload
4.Class hierarchy: override and virtual
5.Use virtual methods and polymorphismUse virtual methods and polymorphism
6.Demonstrate a virtual methodDemonstrate a virtual method
7.When a virtual method is not overridden, the base class method is usedWhen a virtual method is not overridden, 
   the base class method is used
8.illustrates polymorphismillustrates polymorphism
9.Demonstrates the use of a virtual method to override a base class methodDemonstrates the use of a virtual method to override a base class method
10.Method override 3Method override 3
11.Test Polymorphism Virtual Functions