sugy21
sugy21

Reputation: 119

How to obsolete existing method in .Net framework?

My project is global used solution, so I should consider every time for cultural difference.

For instance, I'd like to mark some existing method should not be used in my project.

//warning have to be shown when build or any other way
DateTime temp1 = DateTime.Parse("190101");

//only this code is accepted
bool result = DateTime.TryParseExact("190101", "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime temp2)  

What I want is, I'd like to make some method not to use (or alarming). (not my method, .NET existing method)

Is there any way to achieve that I want?

Upvotes: 2

Views: 186

Answers (2)

Eliano
Eliano

Reputation: 33

For that you need to add this decoration to the method [Obsolete]

Upvotes: -2

Jon Skeet
Jon Skeet

Reputation: 1500435

The simplest option for this is probably to write a Roslyn analyzer. That can analyze your source code, warn you about the methods you don't want to allow, and even suggest a fix. Writing an analyzer isn't a trivial matter, but it's not too bad, at least for simple cases - and I believe your case is reasonably simple.

It's able to react to much more than just "which methods you're allowed to use" too - you might want to validate that TryParseExact is always called with CultureInfo.InvariantCulture, for example. Although you might well be better off creating your own utility class with "parse date", "parse date/time" methods etc, and make your analyzer validate that you're not calling DateTime.Parse/ParseExact/TryParse/TryParseExact anywhere except in that class.

Upvotes: 7

Related Questions