3

It seems that PowerShell method overload resolution system is not consistent with C#

Let's compare

C#

class Program
{
    static void Main(string[] args)
    {
        MyClass.MyMethod(false, DateTime.Now);
    }
}

public static class MyClass
{
    public static void MyMethod(object obj, DateTime dateTime)
    {
        Console.WriteLine("MyClass.MyMethod(object obj, DateTime dateTime)");
    }

    public static void MyMethod(bool b, string str)
    {
        Console.WriteLine("MyClass.MyMethod(bool b, string str)");
    }
}

vs

PowerShell

Add-Type `
@"
    using System;

    public static class MyClass
    {
        public static void MyMethod(object obj, DateTime dateTime)
        {
            Console.WriteLine("MyClass.MyMethod(object obj, DateTime dateTime)");
        }

        public static void MyMethod(bool b, string str)
        {
            Console.WriteLine("MyClass.MyMethod(bool b, string str)");
        }
    }
"@

[MyClass]::MyMethod($false, [DateTime]::Now)

C# will return

MyClass.MyMethod(object obj, DateTime dateTime)

How we expected

But PowerShell will return

MyClass.MyMethod(bool b, string str)

If we want to have the correct method called we have to be more explicit about overload we want to call

[MyClass]::MyMethod([object] $false, [DateTime]::Now)

I think it is a bug in PowerShell, not a feature

The code above was tested in PowerShell 3

In PowerShell 2 the situation is even worse. I could not find a way to call a proper overload

Even this one does not work

 [MyClass]::MyMethod([object] $false, [DateTime] ([DateTime]::Now))

1 Answer 1

3

PowerShell allows for much more type coercion than C# does. For instance, PowerShell will coerce a DateTime to string if that is required (or an int to a bool or a string to a bool). I suspect that the overload resolution is finding a direct type match on the first parameter and then noting the second parameter can be coerced and none of the overloads exactly match types. That said, I happen to agree with you. I would like to see PowerShell get even better with its member overload resolution. In this case, I would say that type compatibility should take precedence over type coercion. Of course, putting a bool in an object reference requires boxing so perhaps that knocked down the scoring for that particular overload.

Consider submitting this issue to the PowerShell team on http://connect.microsoft.com.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.