Spiral Matrix c#

I saw the nick white's solution on youtube, & tried to apply same in c#, But i am getting array out of bound exception. I have checked multiple times , Please can someone help me with this code.

public class Solution {
    public IList<int> SpiralOrder(int[][] matrix) {
          
        
        IList<int> res = new List<int>();
        if (matrix.Length == 0 )
        {
            return res;
        }

        int rowbegin = 0;   // top
        int columnbegin = 0; // left
        int rowend = matrix.GetLength(0) - 1; // bottom
        int columnend = matrix.GetLength(1) - 1; // right 
        int i;
        
        while (rowbegin <= rowend && columnbegin <= columnend)
        {
            
            for (i = columnbegin; i <= columnend; i ++ )
            {
                res.Add((matrix[rowbegin][i]));
            }
            
            rowbegin++;
            
            
            for (i = rowbegin; i <= rowend; i ++ )
            {
                res.Add(matrix[i][columnend]);
            }
            
            columnend--;
            
            if (rowbegin <= rowend)
            {
               
                for (i = columnend; i >= columnbegin; i --)
               {
                res.Add(matrix[rowend][i]);
                }
            }
            
             rowend--;
            
             if (columnbegin <= columnend)
            {
                for (i = rowend; i >= rowbegin; i --)
               {
                res.Add(matrix[i][columnbegin]);
               }
            }
            
            columnbegin++;
            
        }
        
                return res;

        
        
    }
}
Comments (1)