Skip to content

Feature proposal: remove implicit construction of DateTimeOffset from DateTime #32954

Closed as not planned

Description

@slavanap

Specifically these 2 lines of code
https://github.com/dotnet/corert/blob/master/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs#L825-L826

public static implicit operator DateTimeOffset(DateTime dateTime) =>
            new DateTimeOffset(dateTime);

Misleading usecase is that TimeZoneInfo.ConvertTime has 2 overloads for DateTime and DateTimeOffset. When result of the first one is assigned to DateTimeOffset typed variable, DateTimeOffset record with local time zone offset is created. This is unclear for common code reader there's something unintended behaviour may take a place ((hey, I've supplied date, time and timezone to this function, and expect it to return date&time object for this timezone)), because types of either DateTime or DateTimeOffset that comes to ConvertTime argument may be masked by complex computational expression.


If the person wants to shoot their leg, let them do it, but explicitly.

Activity

  1. transferred this issue fromdotnet/corerton Feb 28, 2020
  2. added
    untriaged
    on Feb 28, 2020
  3. added
    api-suggestion
    breaking-change
    on Feb 28, 2020
  4. slavanap commented on Feb 28, 2020

    @slavanap
    Author

    Here's very basic example of the case described

    using System;
    using System.Linq;
    					
    public class Program
    {
        public static readonly DateTime Epoch =
            new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        
        public static readonly TimeZoneInfo EST =
            TimeZoneInfo.GetSystemTimeZones()
                .Where(x => x.Id == "Eastern Standard Time")
                .SingleOrDefault()
            ?? TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); 
    
    
        public static DateTimeOffset UnixEpochToDateTimeOffsetInEST(long msVal)
        {
            return TimeZoneInfo.ConvertTime(Epoch.AddSeconds(msVal), EST);
        }
    
        public static void Main()
        {
            var now = DateTimeOffset.Now;
            Console.WriteLine("Local time = {0}", now);
            Console.WriteLine("UTC time = {0}\n", now.UtcDateTime);
    
    
            var epochNow = Convert.ToInt64((now.UtcDateTime - Epoch).TotalSeconds);
            Console.WriteLine("EST time = {0}", UnixEpochToDateTimeOffsetInEST(epochNow));
    
            // here you get correct time in EST, but local offset.
        }
    }
    
  5. slavanap commented on Mar 9, 2020

    @slavanap
    Author

    I think, marking this implicit operator as obsolote may show a lot of bugs around it.

  6. davidfowl commented on Mar 9, 2020

    @davidfowl
    Member

    Roslyn Analyzer?

  7. Joe4evr commented on Mar 9, 2020

    @Joe4evr
    Contributor

    Or how about Better Obsoletion?

  8. removed
    untriaged
    on Jul 7, 2020
  9. added this to the Future milestone on Jul 7, 2020
  10. bartonjs commented on Jul 15, 2020

    @bartonjs
    Member

    This seems better as an analyzer. The breaking change would be very disruptive, and it should be relatively rare that something accepts both DateTime and DateTimeOffset via overloads.

    I'd even limit the analyzer to identifying the confusing cases, where a DateTime is provided to a method that takes a DateTimeOffset in an overload and the output of that method is a DateTime that is implicitly converted.

    Or maybe it's specifically a problem with TimeZoneInfo.ConvertTime(DateTime, TZI)

  11. slavanap commented on Jul 15, 2020

    @slavanap
    Author

    it should be relatively rare that something accepts both DateTime and DateTimeOffset via overloads.

    A DateTimeOffset typed variable can be constructed from either DateTime or DateTimeOffset.

    This case is pretty often and dangerous when one works with DateTimeOffset typed variables and time conversions.

    Please let me know if the basic example of the issue above that I've listed is not clear.

  12. slavanap commented on Jul 15, 2020

    @slavanap
    Author

    Don't get me wrong, I'm not for removing the constructor, I'm for removing the implicit construction. The one who wants to construct DateTimeOffset from DateTime will still be able to do it, but such obsoletion will force them to list this conversion explicitly, e.g. new DateTimeOffset(DateTime.Now)

  13. bartonjs commented on Jul 15, 2020

    @bartonjs
    Member

    In addition to the obvious source-breaking change, removing the implicit conversion is a binary breaking change which would make .NET (Core) no longer compatible with .NET Standard, so it's unlikely to happen in the foreseeable future.

    The conversion could potentially be marked as [Obsolete], but that would make reasonable code like

    if (someDateTime < someDateTimeOffset)
    {
       ...
    }

    start to get obsoletion warnings. (In point of fact, DateTime/DateTimeOffset is called out in Framework Design Guidelines as doing operators well via the implicit conversion.)

    It feels like an analyzer for identifying where such an implicit conversion is problematic (like the one we added for detecting when an array[range] expression is implicitly converted to a ReadOnlySpan) would provide the value you are seeking without as high of costs.

  14. 19 remaining items

  15. jeffhandley commented on Aug 2, 2021

    @jeffhandley
    Member

    @tarekgh what are the concerns of marking the operator [Obsolete] ? How addition of the attribute can be a breaking change?

    Adding an [Obsolete] attribute will introduce build warnings for anyone already using this operator. Many developers/teams enable treating warnings as errors as well, which then produces a build failure from the usage of the now-obsolete API. We have a high bar for introducing obsoletions since we strive to provide a smooth version-to-version upgrade experience.

    There's some more background on obsoletions here:
    https://github.com/dotnet/designs/blob/main/accepted/2020/better-obsoletion/better-obsoletion.md

  16. IanKemp commented on Aug 19, 2021

    @IanKemp

    @slavanap just because it's possible to blow your own foot off with this API doesn't make it a candidate for obsoletion. I'm sure there are many developers who are using the implicit operator exactly as it's intended, with full understanding of the consequences, who would be very irritated if it started telling them that they should not be using it. As such there is zero chance the .NET team is going to obsolete it simply because you feel strongly about it.

    A Roslyn analyzer is the correct method to address any possible issues with usage of this API. Developers who are using the operator and understand what it's doing can suppress the analyzer's warning, developers who are using it incorrectly can look at the warning and take corrective action, and the 99.99% of developers who ignore all warnings will continue to do so.

  17. slavanap commented on Aug 19, 2021

    @slavanap
    Author

    @IanKemp I'm sorry, I have to ask you, have you read full discussion in the thread?

    If not, here's a short summary for you:

    • There are other developers who run into the issue unintentionally,
    • Developers who want to perform the cast can still do it after deprecation by replacing dt with new DateTimeOffset(dt) or dt.DTO() where DTO is their extension method. The ticket is about to remove implicit construction.
    • conversion of DateTimeOffset to DateTime has an ambiguity to treat any Offset different from local time zone and UTC as Kind.Unspecified which later is treated similarly to Kind.Local in other operations. If you use DateTimeOffset with only local or UTC timezones the bug is not visible to you.
  18. Shivian444 commented on Jun 29, 2022

    @Shivian444

    @tarekgh what are the concerns of marking the operator [Obsolete] ? How addition of the attribute can be a breaking change?

    Adding an [Obsolete] attribute will introduce build warnings for anyone already using this operator. Many developers/teams enable treating warnings as errors as well, which then produces a build failure from the usage of the now-obsolete API. We have a high bar for introducing obsoletions since we strive to provide a smooth version-to-version upgrade experience.

    There's some more background on obsoletions here: https://github.com/dotnet/designs/blob/main/accepted/2020/better-obsoletion/better-obsoletion.md

    Can we have say a compiler directive to block it at solution level then? If our solution would explicitly never want this behavior I think it would make sense to have some sort of control on implicit behaviors like these.

  19. tannergooding commented on Sep 9, 2022

    @tannergooding
    Member

    CC. @tarekgh, is this an issue we should keep open or close?

    If we should keep it open, is it near a point where it can be marked ready for review?

  20. tarekgh commented on Sep 9, 2022

    @tarekgh
    Member

    I don't think we'll go with the proposal. As suggested, adding analyzer rule for it would be better as there is no agreement on the obsoletion.

  21. danmoseley commented on Sep 9, 2022

    @danmoseley
    Contributor

    Do we have an issue tracking a potential analyzer? I hit this recently myself and it's insidious

  22. tarekgh commented on Sep 10, 2022

    @tarekgh
    Member

    I don't think there is an analyzer issue for that. We can open one or repurpose this issue to the analyzer.

  23. tarekgh commented on Sep 10, 2022

    @tarekgh
    Member

    I have opened the analyzer issue to track adding the analyzer for this implicit operator. if all agree, we can close this issue now and follow up with the analyzer issue.

  24. danmoseley commented on Sep 10, 2022

    @danmoseley
    Contributor

    I agree

  25. ghost locked as resolved and limited conversation to collaborators on Oct 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.DateTimebreaking-change

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions