Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw exception when trying to register a closed generic type. #268

Merged
merged 2 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/DynamicExpresso.Core/ReferenceType.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
Expand All @@ -25,6 +25,14 @@ public ReferenceType(string name, Type type)
if (type == null)
throw new ArgumentNullException(nameof(type));

if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
var genericType = type.GetGenericTypeDefinition();
var genericTypeName = genericType.Name.Substring(0, genericType.Name.IndexOf('`'));
genericTypeName += $"<{new string(',', genericType.GetGenericArguments().Length - 1)}>";
throw new ArgumentException($"Generic type must be referenced via its generic definition: {genericTypeName}");
}

Type = type;
Name = name;
ExtensionMethods = ReflectionExtensions.GetExtensionMethods(type).ToList();
Expand Down
19 changes: 18 additions & 1 deletion test/DynamicExpresso.UnitTest/ReferencedTypesPropertyTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace DynamicExpresso.UnitTest
Expand Down Expand Up @@ -37,5 +39,20 @@ public void Registering_custom_known_types()
public class FakeClass
{
}

[Test]
public void Registering_generic_types()
{
var target = new Interpreter(InterpreterOptions.None);

var exception = Assert.Throws<ArgumentException>(() => target.Reference(typeof(List<string>)));
Assert.That(exception.Message, Contains.Substring("List<>"));

exception = Assert.Throws<ArgumentException>(() => target.Reference(typeof(Tuple<string, string, int>)));
Assert.That(exception.Message, Contains.Substring("Tuple<,,>"));

Assert.DoesNotThrow(() => target.Reference(typeof(List<>)));
Assert.DoesNotThrow(() => target.Reference(typeof(Tuple<,,>)));
}
}
}