Generic Method with Unknown Number of Dimensions

Nathan Sokalski 4,111 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?

Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    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 122.6K 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( );  
        }  
    }  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.