dbolkensteyn
7/21/2015 - 1:42 PM

UsingNewToHideAMethod.cs

// Suggested rule: warn on the use of "new" to hide methods

using System;

namespace VS2013ConsoleApplication1.RoslynRule_samples
{

    public class MyBaseType
    {
        public int GetData()
        {
            return 111;
        }
    }

    public class MyChildType : MyBaseType
    {
        // Use the "new" keyword to indicate we intended to hide the parent method.
        // Amazing, the code will compile without the "new" method, although there is a warning:
        // CS0108: https://msdn.microsoft.com/en-us/library/3s8070fc.aspx.
        public new int GetData()
        {
            return 222;
        }
    }

    static class MethodHidingExample
    {
        public static void EntryPoint()
        {
            MyChildType childRef = new MyChildType();
            MyBaseType baseRef = childRef;

            // There is only one instance of the object here, but the value you get back
            // depends on the type of variable.
            Console.WriteLine("Object: {0}, data: {1}", baseRef.GetHashCode(),  baseRef.GetData()); // returns 111
            Console.WriteLine("Object: {0}, data: {1}", childRef.GetHashCode(), childRef.GetData()); // returns 222

            // Impact: confusing and unexpected behaviour for callers (particularly if they
            // don't have access to the source code) and can cause hard-to-find bugs.
            // It's also indicative that there is something wrong with the design.

            // There are a couple of discussions on stackoverflow about when if ever this is acceptable
            //   e.g. http://stackoverflow.com/questions/451035/use-new-keyword-if-hiding-was-intended

            // The existing warning CS0108 tells users to be explicit about hiding the method.
            // It would better to tell them not to do it all.
        }

    }
}