nickdodd79 / AutoBogus

A C# library complementing the Bogus generator by adding auto creation and population capabilities.
MIT License
431 stars 50 forks source link

Keywork IN on constructors throws #40

Closed SuricateCan closed 4 years ago

SuricateCan commented 4 years ago

Hi, I just noticed this error and could not find a reference anywhere:

System.ArgumentException : The type 'System.Int64&' may not be used as a type argument.
   at System.RuntimeType.ThrowIfTypeNeverValidGenericArgument(RuntimeType type)
   at System.RuntimeType.SanityCheckGenericArguments(RuntimeType[] genericArguments, RuntimeType[] genericParamters)
   at System.RuntimeType.MakeGenericType(Type[] instantiation)
   at AutoBogus.AutoGeneratorFactory.CreateGenericGenerator(Type generatorType, Type[] genericTypes)
   at AutoBogus.AutoGeneratorFactory.ResolveGenerator(AutoGenerateContext context)
   at AutoBogus.AutoGeneratorFactory.GetGenerator(AutoGenerateContext context)
   at AutoBogus.AutoBinder.GetParameterGenerator(ParameterInfo parameter, AutoGenerateContext context)
   at AutoBogus.AutoBinder.<>c__DisplayClass0_0`1.<CreateInstance>b__0(ParameterInfo p)
   at System.Linq.Utilities.<>c__DisplayClass2_0`3.<CombineSelectors>b__0(TSource x)
   at System.Linq.Enumerable.SelectArrayIterator`2.ToArray()
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at AutoBogus.AutoBinder.CreateInstance[TType](AutoGenerateContext context)
   at AutoBogus.Generators.TypeGenerator`1.AutoBogus.IAutoGenerator.Generate(AutoGenerateContext context)
   at AutoBogus.AutoGenerateContextExtensions.Generate[TType](AutoGenerateContext context)
   at AutoBogus.AutoFaker.AutoBogus.IAutoFaker.Generate[TType](Action`1 configure)
   at AutoBogus.AutoFaker.Generate[TType](Action`1 configure)

After some digging, I realized that the error was actually caused by one of my constructor arguments: MyClass(in long p). As soon as I removed the in keyword (MyClass(long p)), the error disappeared.

So, for those fortunate enough to find this thread, the simple solution is to remove the in keyword.

However I've opened this issue cause I believe that the method below should "sanitize" the type before proceeding.

https://github.com/nickdodd79/AutoBogus/blob/975277908fd60a302547576973766c1e1dc6663f/src/AutoBogus/AutoBinder.cs#L156-L162

in keyword is part of C#7.2 as explained here.

You can check the parameter using the property type.IsByRef. Also, the name of the type ends with &. To get the real type, type.GetElementType().

Passing the element type should fix the issue for those using C#7.2

nickdodd79 commented 4 years ago

Hey @SuricateCan

I have added your suggested code change and believe v2.10.0 should now work for you.

Nick.

SuricateCan commented 4 years ago

Hi @nickdodd79. I've testes 2.10.0 and it work as expected. Thanks a lot!