#679 – Hide An Inherited Method with A Virtual Method

You typically hide an inherited method using the new keyword, indicating that the method should not behave polymorphically.  If you later inherit this method in a subclass, you won’t be able to override the method marked as new.

For example:

  • virtual Dog.Bark  – can override
  • new Terrier.Bark – hides Dog.Bark
  • new Yorkshire.Bark – must hide, can’t override

However, if you want to hide an inherited method, but still allow overriding in a subclass, you can use the virtual new combination:

  • virtual Dog.Bark – can override
  • virtual new Terrier.Bark – hides Dog.Bark, but allows overriding
  • override Yorkshire.Bark – overrides Terrier.Bark

In this case, Terrier and Yorkshire objects referenced by variables of type Dog will not behave polymorphically.  But a Yorkshire object referenced by a Terrier variable will behave polymorphically.

 

Advertisements

#678 – A Sealed Method Cannot Be Overridden

When you override a method, you create a virtual method that behaves polymorphically.  The base class defines the method using the virtual keyword and you define the method in your child class using the override keyword.

When you use the override keyword, your method can itself be overridden in a child class.

If you want to override a method in a base class, but also prevent any derived classes from overriding your method, you can use the sealed keyword to indicate that a child class must use the new keyword, rather than overriding your method.

    public class Dog
    {
        public virtual void Bark()
        {
            Console.WriteLine("  Dog.Bark");
        }
    }

    public class Terrier : Dog
    {
        public sealed override void Bark()
        {
            Console.WriteLine("  Terrier is barking");
        }
    }

    public class JRT : Terrier
    {
        public new void Bark()
        {
            Console.WriteLine("  JRT is barking");
        }
    }

#677 – Method Marked with new Modifier Cannot Be Overridden

You can use the new modifier on a method to indicate that the method should hide a method of the same name in a base class.  In other words, the method does not behave polymorphically.

If you’ve marked a method as new in a class, that method is not virtual and can not be overridden in a derived class.

In the example below, the Dog class marks Bark as virtual, indicating that it can be overridden.  The Terrier class marks Bark as new, indicating that it does not override Dog.Bark–and that it cannot be overridden.  JRT can therefore not override Bark.

    public class Dog
    {
        public virtual void Bark()
        {
            Console.WriteLine("  Dog.Bark");
        }
    }

    public class Terrier : Dog
    {
        public new void Bark()
        {
            Console.WriteLine("  Terrier is barking");
        }
    }

    public class JRT : Terrier
    {
        public new void Bark()
        {
            Console.WriteLine("  JRT is barking");
        }
    }

#676 – An Overridden Method Can Itself Be Overridden

To get polymorphic behavior for a method in a derived class, you need to mark the method in the base class as virtual and the method in the derived class as override.  This allows the method in the derived class to be called at runtime, even when referenced by a variable whose type is the base class.

    public class Dog
    {
        public virtual void Bark()
        {
            Console.WriteLine("  Dog.Bark");
        }
    }

    public class Terrier : Dog
    {
        public override void Bark()
        {
            Console.WriteLine("  Terrier is barking");
        }
    }

The Bark method in Terrier overrides the version in Dog.  But the override method also indicates that the Bark method can itself be overridden in a class that derives from Terrier.

    public class JRT : Terrier
    {
        public override void Bark()
        {
            Console.WriteLine("  JRT is barking");
        }
    }

The Bark method is now polymorphic across all three types.

#675 – Polymorphic Behavior Requires virtual / override Combination

Recall that polymorphism means that the type of an object at run-time is used to decide what method to call, rather than the static type of the variable that references that object.

In C#, a method behaves polymorphically if and only if the method in the base class is defined as virtual and the method in the derived class is defined as override.  

For example, if Terrier inherits from Dog, we can declare a Dog.Bark method as virtual and a Terrier.Bark method as override.  We then get polymorphic behavior:

Terrier t = new Terrier("Jack");
Dog d = t;

// Polymorphic behavior =
//   Terrier's implementation of Bark is called,
//   because type of object referenced by d is
//   determined at runtime.
d.Bark();

#419 – Override Relational Operators When You Implement IComparable

When a class implements IComparable, it must implement the CompareTo method.  For completeness, you should also override the relational operators.

Here’s an example.

    public class Rectangle : IEquatable<Rectangle>, IComparable<Rectangle>
    {
        public int Height { get; set; }
        public int Width { get; set; }

        public Rectangle(int height, int width)
        {
            Height = height;
            Width = width;
        }

        public override bool Equals(object obj)
        {
            return this.Equals(obj as Rectangle);
        }

        public override int GetHashCode()
        {
            return Height.GetHashCode() ^ Width.GetHashCode();
        }

        public bool Equals(Rectangle r)
        {
            if (ReferenceEquals(r,null))
                return false;

            return ((Height == r.Height) && (Width == r.Width) ||
                    (Height == r.Width) && (Width == r.Height));
        }

        public static bool operator ==(Rectangle r1, Rectangle r2)
        {
            if (ReferenceEquals(r1, null))
            {
                return ReferenceEquals(r2, null) ? true : false;
            }

            return r1.Equals(r2);
        }

        public static bool operator !=(Rectangle r1, Rectangle r2)
        {
            return !(r1 == r2);
        }

        // Result:
        //  < 0 : this instance less than r
        //  = 0 : this instance equivalent to r
        //  > 0 : this instance greater than r
        public int CompareTo(Rectangle r)
        {
            if (ReferenceEquals(r, null))
                return 1;  

            if (this.Equals(r))
                return 0;

            else if (this.Area() == r.Area())
                return this.Width - r.Width;

            else
                return this.Area() - r.Area();
        }

        public static bool operator <(Rectangle r1, Rectangle r2)
        {
            if (ReferenceEquals(r1, null))
                return false;

            else
                return (r1.CompareTo(r2) < 0) ? true : false;
        }

        public static bool operator >(Rectangle r1, Rectangle r2)
        {
            if (ReferenceEquals(r1, null))
                return false;

            else
                return (r1.CompareTo(r2) > 0) ? true : false;
        }

        public static bool operator <=(Rectangle r1, Rectangle r2)
        {
            return (r1 < r2) || (r1 == r2);
        }

        public static bool operator >=(Rectangle r1, Rectangle r2)
        {
            return (r1 > r2) || (r1 == r2);
        }

        public int Area()
        {
            return Height * Width;
        }
    }

#360 – Property Modifiers Required for Polymorphic Behavior

There are three combinations of modifiers that make sense, in determining whether properties in a class are virtual or non-virtual.

Typical combinations of modifiers for base class / derived class (assuming that the property’s name and type are the same in both the base and derived class):

  • (no modifier) / new – Both properties are non-virtual, derived class property hides the base class property
  • virtual / override – Both properties are virtual and support polymorphic behavior
  • virtual / new – Base class property is virtual, derived class property is non-virtual, derived class property hides the base class property

There are two other combinations that are allowed, but result in a compiler warning indicating that you should use new in the derived class to be explicit:

  • (no modifier) / (no modifier) – is equivalent to: (no modifier) / new
  • virtual / (no modifier) – is equivalent to: virtual / new