Generic Method with Unknown Number of Dimensions

Nathan Sokalski 4,126 Reputation points
2022-09-23T17:53:53.03+00:00

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?

C#
C#
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,648 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2022-09-25T15:39:57.367+00:00

    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 114.7K Reputation points
    2022-09-25T18:24:26.82+00:00

    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]];  
        }  
        else  
        {  
            return Enumerable.Repeat( CreateJagged<T>( dimensions.Skip( 1 ).ToArray( ) ), dimensions[0] ).ToArray( );  
        }  
    }