Skip to content

Commit 2063ffc

Browse files
0xcedmoh-hassan
authored andcommitted
Fix NullReferenceException when creating a default immutable instance (#495)
* Fix NullReferenceException when creating a default immutable instance * Improve exception message when immutable type can't be created
1 parent f184e77 commit 2063ffc

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

src/CommandLine/Core/InstanceBuilder.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ private static T BuildImmutable<T>(Type typeInfo, Maybe<Func<T>> factory, IEnume
167167

168168
if(ctor == null)
169169
{
170-
throw new InvalidOperationException($"Type appears to be immutable, but no constructor found for type {typeInfo.FullName} to accept values.");
170+
throw new InvalidOperationException($"Type {typeInfo.FullName} appears to be immutable, but no constructor found to accept values.");
171171
}
172172

173173
var values =

src/CommandLine/Infrastructure/ReflectionHelper.cs

+5
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,11 @@ public static T CreateDefaultImmutableInstance<T>(Type[] constructorTypes)
9191
public static object CreateDefaultImmutableInstance(Type type, Type[] constructorTypes)
9292
{
9393
var ctor = type.GetTypeInfo().GetConstructor(constructorTypes);
94+
if (ctor == null)
95+
{
96+
throw new InvalidOperationException($"Type {type.FullName} appears to be immutable, but no constructor found to accept values.");
97+
}
98+
9499
var values = (from prms in ctor.GetParameters()
95100
select prms.ParameterType.CreateDefaultForImmutable()).ToArray();
96101
return ctor.Invoke(values);

tests/CommandLine.Tests/Unit/Core/InstanceBuilderTests.cs

+11-1
Original file line numberDiff line numberDiff line change
@@ -1063,7 +1063,17 @@ public void OptionClass_IsImmutable_HasNoCtor()
10631063
{
10641064
Action act = () => InvokeBuild<ValueWithNoSetterOptions>(new string[] { "Test" }, false, false);
10651065

1066-
act.Should().Throw<InvalidOperationException>();
1066+
act.Should().Throw<InvalidOperationException>()
1067+
.Which.Message.Should().Be("Type CommandLine.Tests.Unit.Core.InstanceBuilderTests+ValueWithNoSetterOptions appears to be immutable, but no constructor found to accept values.");
1068+
}
1069+
1070+
[Fact]
1071+
public void OptionClass_IsImmutable_HasNoCtor_HelpRequested()
1072+
{
1073+
Action act = () => InvokeBuild<ValueWithNoSetterOptions>(new string[] { "--help" });
1074+
1075+
act.Should().Throw<InvalidOperationException>()
1076+
.Which.Message.Should().Be("Type CommandLine.Tests.Unit.Core.InstanceBuilderTests+ValueWithNoSetterOptions appears to be immutable, but no constructor found to accept values.");
10671077
}
10681078

10691079
[Fact]

0 commit comments

Comments
 (0)