0

I am trying to call create an immutable array given an object variable that actually has a type of an T[] under the hood. How to do that using a Reflection. The problem is ImmutableArray.Create has many overloads and I get an ambigous method exception.

var method = typeof(ImmutableArray).GetMethod(nameof(ImmutableArray.Create)).Invoke(null, arr);
Node.JS
  • 1,042
  • 6
  • 44
  • 114

1 Answers1

0

This is how I resolved the problem of finding a ImmutableArray<T> Create<T>(params T[]? items) method and calling it given an array.

var method = typeof(ImmutableArray)
  .GetMethods()
  .Where(m => m is { Name: nameof(ImmutableArray.Create), IsPublic: true, IsGenericMethod: true })
  .Single(m => m.GetParameters().Length == 1 &&
              m.GetParameters()[0].GetCustomAttribute<ParamArrayAttribute>() != null &&
              m.GetParameters()[0].ParameterType is { IsArray: true });

var immutableArrayCreateMethodInfo = method.MakeGenericMethod(arr.GetType());

immutableArrayCreateMethodInfo.Invoke(null, new[] { arr });
Node.JS
  • 1,042
  • 6
  • 44
  • 114