Method call behaves differently in PowerShell than in a compiled C# application
See original GitHub issueNote: The [datetime]::ParseExact()
method used below is the only one I’ve seen the problem with - I have no idea what underlies this symptom and how general the problem is.
If you run the code below in the following environments:
-
(a) as PowerShell code
-
(b) as C# code compiled on demand with
Add-Type
-
© as C# code compiled to a .NET Core 2.1 / 3.0-preview8 console application
only © works as expected.
Steps to reproduce
The following code should yield 1921
:
# Set the 2-digit-year threshold to 2020, so that '21' is interpreted as *19*21
($c = [CultureInfo]::InvariantCulture.Clone()).Calendar.TwoDigitYearMax = 2020; [datetime]::ParseExact('21', 'yy', $c).Year
# Run the equivalent C# code via Add-Type
Add-Type @'
using System;
using System.Globalization;
public static class Program
{
public static void Main(string[] args)
{
var cc = (CultureInfo)CultureInfo.InvariantCulture.Clone();
cc.Calendar.TwoDigitYearMax = 2020;
Console.WriteLine(DateTime.ParseExact("21", "yy", cc).Year);
}
}
'@
[Program]::Main(@())
Expected behavior
1921
1921
Actual behavior
2021
2021
That is, the modified .TwoDigitYearMax
property value was ignored.
Note:
-
If you run the exact same code as passed to
Add-Type
above as a .NET Core application, the result is as expected. -
The problem may be related to calling
.Clone()
on the static[CultureInfo]::InvariantCulture
property, because it goes away if you obtain the invariant culture with[CultureInfo] ''
or[CultureInfo]::GetCultureInfo('')
instead (while the resulting object looks the same, there’s no reference equality)
Environment data
PowerShell Core 7.0.0-preview.2
Windows PowerShell 5.1.17763.592
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (2 by maintainers)
You’re right regarding the property - actually just accessing
.DateTimeFormat
is enough. So probably my guess regarding offending line is incorrect. 😃Thanks, @lpatalas - great stuff (it is accessing
.DateTimeFormat.Calendar
, not.Calendar
, before cloning that triggers the bug).I’ve created a CoreFx bug report at https://github.com/dotnet/corefx/issues/40953
So it sounds like PowerShell surfaces the bug accidentally, by virtue of the reflection it performs behind the scenes, correct?
I’m closing this, as it appears to be purely a CoreFx issue, even though PowerShell happens to surface it consistently.