Declaring a method that takes an array of any datetype?

mp3909

Well-known member
Joined
Apr 22, 2018
Messages
61
Location
UK
Programming Experience
3-5
In the code below, I am asking the user to give the dimensions of a multidimensional array.
The user is then told to enter the values for the array.
I then want to display the contents of an array by passing it to a method called display.
The question I have is that how can I make this method accept an array of any data type?
Say if I create an array that holds string data types and I want to display its contents, then I don't want to create a separate method for this. I want to be able to still pass it to the same method.
Thanks!



C#:
using System;
public class Program
{
       public static void Main()
       {
          Console.WriteLine("Enter the number of rows: ");
          int rows = int.Parse(Console.ReadLine());
  
          Console.WriteLine("Enter the number of columns: ");
          int cols = int.Parse(Console.ReadLine());
   
          int[,] matrix = new int[rows,cols];
  
          Console.WriteLine("Enter the values for your matrix");
  
          for(int x=0; x<rows; x++)
          {
               for(int y=0; y<cols; y++)
              {
                   matrix[x,y] = int.Parse(Console.ReadLine());
              }
          }
  
          Program.display(matrix);
       }

       public static void display([COLOR=#00ff00]??[/COLOR] [,] arr)  //what datatype to use here for the array if this method can accept string,float,int etc?
       {
                  for(int x=0; x<arr.GetLength(0); x++)
                  {
                       for(int y=0; y<arr.GetLength(1); y++)
                       {
                           Console.Write(arr[x,y] + " ");
                       }
                  Console.WriteLine();
                  }
        }
}
 
You can write a generic method for this:
public static void Display<T>(T[,] arr)  //what datatype to use here for the array if this method can accept string,float,int etc?
{
    for(int x=0; x<arr.GetLength(0); x++)
    {
        for(int y=0; y<arr.GetLength(1); y++)
        {
            Console.Write(arr[x,y].ToString() + " ");
        }

        Console.WriteLine();
    }
}
 
Hi, jmcilhinney
I'm trying to figure out how to call this method. I tried with:
C#:
string[] sa = { "a", "b", "c" };
 Display<string>(sa);
or
C#:
Display<string>(string["a", "b", "c"]);

But I'm getting errors and I don't quite understand how to pass the arguments.
 
Hi, jmcilhinney
I'm trying to figure out how to call this method. I tried with:
C#:
string[] sa = { "a", "b", "c" };
 Display<string>(sa);
or
C#:
Display<string>(string["a", "b", "c"]);

But I'm getting errors and I don't quite understand how to pass the arguments.

You create an array in any normal way and then simply call Display and pass the array, e.g.
var strings = new [] {"a", "b", "c"};

Display(strings);

You don't need to specify T explicitly when you call Display because it is inferred from the argument. The parameter is declared to be an array of T so if you pass an array of String then that fixes T to be String.
 
Thanks for answering jmcilhinney ,
I still get an error (commented it in the code) :

using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleApplication4
{
    class Program
    {
        // [url]http://www.csharpforums.net/showthread.php/3950-Declaring-a-method-that-takes-an-array-of-any-datetype?p=9309#post9309[/url]
        // You can write a generic method for this:
        public static void Display<T>(T[,] arr)  // what datatype to use here for the array if this method can accept string,float,int etc?
        {
            for (int x = 0; x < arr.GetLength(0); x++)
            {
                for (int y = 0; y < arr.GetLength(1); y++)
                {
                    Console.Write(arr[x, y].ToString() + " ");
                }


                Console.WriteLine();
            }
        }
        static void Main(string[] args)
        {


            var strings = new[] { "a", "b", "c" };


            Display(strings);
            // The above yields the following error:
            /* Error    1    
            * The type arguments for method 'ConsoleApplication4.Program.Display<T>(T[*,*])' cannot be inferred from the usage.
            * Try specifying the type arguments explicitly.
            */
        }
    }
}
 
Your request and the Display method posted is for multidimensional array, then later you try to use single dimensional array. If this was the sample it would work as expected:
var strings = new[,] { { "a", "b" }, { "c", "d" } };
 
Your request and the Display method posted is for multidimensional array, then later you try to use single dimensional array. If this was the sample it would work as expected:
var strings = new[,] { { "a", "b" }, { "c", "d" } };

Thank you JohnH !
Indeed now I see that it requires T[,] argument - my eyes are just not adjusted to C#
 
Thank you JohnH !
Indeed now I see that it requires T[,] argument - my eyes are just not adjusted to C#

Mine too, apparently. I hadn't looked at this thread for a while and I too missed the fact that it was a 2D array. You certainly could reimplement Display for a 1D array.
 
You certainly could reimplement Display for a 1D array.


Yes, exactly what I did in order to understand it -
public static void DisplaySignleArray<T>(T[] arr)  // what datatype to use here for the array if this method can accept string,float,int etc?
{
  for (int i = 0; i < arr.GetLength(0); i++)
    {
      Console.Write(arr[i].ToString() + " ");
    }
  }



Mine too, apparently. I hadn't looked at this thread for a while and I too missed the fact that it was a 2D array.


Yeah, problem is that some of us are too fresh/green (or atleast me), so error-free examples are required at that point (else it becomes too frustrating to debug).
Last question, under what category of C# is covered this - I assume its the generics one?
 
Last question, under what category of C# is covered this - I assume its the generics one?

This is a generic method so that section probably should cover this topic, if not provide an example specifically of using an array.
 
Back
Top Bottom