Generic Method with Unknown Number of Dimensions

Nathan Sokalski 4,121 Reputation points

I have a Generic Method in which the return type will be a Jagged Array. However, the number of dimensions is unknown at design time (the return type could end up being T[], T[][], T[][][], or even T[][][][][][][][][]). It would be very inefficient to create an overload for all scenarios. Is there a way to dynamically specify the number of dimensions in the return type?

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,401 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce ( 58,121 Reputation points

    No, you need an overload for each. MS ran into the same issue with Tuple<>, and needed to keep making it more overloads. c# would need a macro system like rust to be able to do this.

    As suggested you need all the overloads, or use an object.and cast the method results or use dynamic.

  2. Viorel 113.2K Reputation points

    If the question is how to write the function, then try an approach:

    static object CreateJagged<T>( int[] dimensions )  
        if( dimensions.Length == 1 )  
            return new T[dimensions[0]];  
            return Enumerable.Repeat( CreateJagged<T>( dimensions.Skip( 1 ).ToArray( ) ), dimensions[0] ).ToArray( );