Created
July 21, 2015 13:42
-
-
Save dbolkensteyn/95ea63ebaac941bbce8a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment