1

Is there any way that in project level I can define rule set that give me compile time error while using some properties? Like In my project i want to enforced that No one should use DateTime.Now . IF some one use it , project should be give compile time error.

I am using Dot net 6 Minimal API project and using Visual studio 2022. (I also have license of resharper, please provide solution if possible via Resharper)

Darshit Gandhi
  • 121
  • 1
  • 7
  • 1
    I would be fairly sure there is nothing builtin, you could probably write something yourself, or just write a simple script that searches all code files for "DateTime.Now" and fails the CI build if found. But what is the actual problem you are trying to solve? Because this sounds like you are trying to solve a training problem with technology, and that might not work very well. – JonasH Jul 19 '23 at 08:21
  • Actually we have lots of repositories and Many leads that handle some small teams. @JonasH I want to make sure no one commit code with DateTime.now as it generate many run time issue. – Darshit Gandhi Jul 20 '23 at 05:24
  • 1
    There is nothing *inherently* wrong with DateTime.Now. It might be incorrect in some *contexts*, but there are infinite ways to write incorrect code, you cannot protect against all of them. – JonasH Jul 20 '23 at 06:40
  • Yes, You are right. but i am trying to prevent loss in terms of money for my client. We strictly need DateTime.Utcnow instead of DateTime.now. – Darshit Gandhi Jul 20 '23 at 07:51
  • 1
    DateTime knows what "kind" it is, so you can check if the kind is correct whenever you accept it as a parameter, and either convert it automatically, or throw an error. Unit tests can also be useful to verify that any DateTimes has the correct kind. – JonasH Jul 20 '23 at 08:14
  • 1
    If you are dealing with multiple time zones I would consider using something like nodaTime, That would likely reduce the risk of mistakes. – JonasH Jul 20 '23 at 08:20
  • I am just using DateTime. utcnow and we don't have test cases – Darshit Gandhi Jul 20 '23 at 11:55
  • 1
    I'd write a Roslyn analyzer for this: https://stackoverflow.com/questions/58970000/find-all-usages-of-datetime-now-today-utcnow-with-a-roslyn-analyzer – mu88 Jul 25 '23 at 12:23

0 Answers0