Skip to content

Commit 8600d8d

Browse files
committed
Fix: allow calling C# class constructor with snake-cased arguments
1 parent 8fb227a commit 8600d8d

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/embed_tests/TestMethodBinder.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,24 @@ def call_method(instance):
898898
Assert.IsFalse(Exceptions.ErrorOccurred());
899899
}
900900

901+
[Test]
902+
public void BindsConstructorToSnakeCasedArgumentsVersion()
903+
{
904+
using var _ = Py.GIL();
905+
906+
var module = PyModule.FromString("CallsCorrectOverloadWithoutErrors", @"
907+
from clr import AddReference
908+
AddReference(""System"")
909+
from Python.EmbeddingTest import *
910+
911+
def create_instance():
912+
return TestMethodBinder.CSharpModel(some_argument=1, another_argument=""another argument value"")
913+
");
914+
var exception = Assert.Throws<ClrBubbledException>(() => module.GetAttr("create_instance").Invoke());
915+
var sourceException = exception.InnerException;
916+
Assert.IsInstanceOf<NotImplementedException>(sourceException);
917+
Assert.AreEqual("Constructor with arguments", sourceException.Message);
918+
}
901919

902920
// Used to test that we match this function with Py DateTime & Date Objects
903921
public static int GetMonth(DateTime test)
@@ -918,6 +936,12 @@ public CSharpModel()
918936
new TestImplicitConversion()
919937
};
920938
}
939+
940+
public CSharpModel(int someArgument, string anotherArgument = "another argument")
941+
{
942+
throw new NotImplementedException("Constructor with arguments");
943+
}
944+
921945
public void TestList(List<TestImplicitConversion> conversions)
922946
{
923947
if (!conversions.Any())

src/runtime/ClassManager.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,11 @@ void AddMember(string name, string snakeCasedName, bool isStaticReadonlyCallable
552552
methodList = methods[name] = new ();
553553
}
554554
methodList.Add(ctor, true);
555+
// Same constructor, but with snake-cased arguments
556+
if (ctor.GetParameters().Any(pi => pi.Name.ToSnakeCase() != pi.Name))
557+
{
558+
methodList.Add(ctor, false);
559+
}
555560
continue;
556561

557562
case MemberTypes.Property:

0 commit comments

Comments
 (0)