Within the following example I can produce a virtual method Show() within the inherited class after which override it within the getting class.

I wish to perform the same factor using the protected class variable prefix however i obtain the error:

The modifier 'virtual' isn't valid with this item

Consider I can not define this variable as virtual/override during my classes, I recieve the compiler warning:

TestOverride234355.SecondaryTransaction.prefix' hides inherited member 'TestOverride234355.Transaction.prefix'. Make use of the new keyword if hiding was intended.

Fortunately after i add the new keyword everything works fine, that is ok since i have obtain the same functionality, but this boosts two questions:

  1. Why I'm able to use virtual/override for techniques although not for protected class variables?

  2. What's the difference really between your virtual/override approach and also the hide-it-with-new approach since a minimum of within this example they provide exactly the same functionality?

Code:

using System;

namespace TestOverride234355
{
    public class Program
    {
        static void Main(string[] args)
        {
            Transaction st1 = new Transaction { Name = "name1", State = "state1" };
            SecondaryTransaction st2 = 
                new SecondaryTransaction { Name = "name1", State = "state1" };

            Console.WriteLine(st1.Show());
            Console.WriteLine(st2.Show());

            Console.ReadLine();
        }
    }

    public class Transaction
    {
        public string Name { get; set; }
        public string State { get; set; }

        protected string prefix = "Primary";

        public virtual string Show()
        {
            return String.Format("{0}: {1}, {2}", prefix, Name, State);
        }
    }

    public class SecondaryTransaction : Transaction
    {
        protected new string prefix = "Secondary";

        public override string Show()
        {
            return String.Format("{0}: {1}, {2}", prefix, Name, State);
        }
    }
}

Rather produce a property for that prefix member - by doing this you are able to set the home to virtual/abstract

Fields are utilized to store condition to have an object, they assist the item encapsulate data and hide implementation concerns from others. By having the ability to override a area we're seeping the implementation concerns from the class to client code (including subtypes). Because of this most languages took your decision that certain cannot define instance variables that may be overridden (although they may be public/protected... so that you can access them).

Additionally you cannot put instance variables within an interface