While removing some obsolete code I came across an unexpected scenario, recreated below:
class Program { static void Main(string[] args) { ViableMethod(); Console.WriteLine(""); SoftDeprecatedMethod();//Compiler warning //HardDeprecatedMethod();//Can't call that from here, compiler error Console.ReadKey(true); } public static void ViableMethod () { Console.WriteLine("ViableMethod, calls SoftDeprecatedMethod"); SoftDeprecatedMethod();//Compiler warning //HardDeprecatedMethod();//Can't call that from here, compiler error } [Obsolete("soft", false)] public static void SoftDeprecatedMethod() { Console.WriteLine("SoftDeprecatedMethod, calls HardDeprecatedMethod"); HardDeprecatedMethod(); } [Obsolete("hard", true)] public static void HardDeprecatedMethod() { Console.WriteLine("HardDeprecatedMethod"); } }
Based in the output it seems that functions deprecated with a warning are permitted to call functions deprecated with an error and the code will execute.
My expectation was that I would see a compiler error complaining that the call to HardDeprecatedMethod()
from SoftDeprecatedMethod()
is not permitted. The observed behavior seems odd to me.
Does anyone know if this is the desired behavior (and if so, why), or could this be a flaw in the implementation of the [Obsolete]
attribute?
Obsolete attributes are used to display an error or warning during compilation with an optional message to alert the developer that the given type or its member should not be used in the code as it is going to be replaced.
What's an obsolete method? A method in a class library which is old or out-of-use and some other method instead of this is suggested to be used.
The Obsolete Attribute marks elements like classes, methods, properties, fields, delegates, and many others within our code as deprecated or obsolete. The attribute is read at compile time and it is used to generate a warning or an error to the developer.
By marking it as obsolete you are saying that it is indeed obsolete, so no need to restate it in the message. Especially since the resulting warning/error will read 'Method1' is obsolete: 'Method1 is deprecated, please use Method2 instead. '
In facts it's the other way around: It shows that C# compiler is smart and very clear on the use of methods marked with Obsolete
.
Assume that you are providing this code as a public API in a class library to Bob.
You expect if Bob calls HardDeprecatedMethod
in his code, he should get a compile time error; and he will.
You expect if Bob has called SoftDeprecatedMethod
anywhere, from this time forward, he should be warned about that, BUT his code should still work; and it will.
So you get what exactly you want!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With