Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,011 questions

51,958 answers

573 users

How to handle 1D and 2D arrays in the same method with C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Print(Array array)
        {
            switch (array.Rank)
            {
                case 1:
                    for (int i = 0; i < array.Length; i++) {
                        Console.Write("{0, 3}", array.GetValue(i));
                    }
                    Console.WriteLine();
                    break;
                case 2:
                    for (int i = 0; i < array.GetLength(0); i++) {
                        for (int j = 0; j < array.GetLength(1); j++) {
                            Console.Write("{0, 3}", array.GetValue(i, j));
                        }
                        Console.WriteLine();
                    }
                    break;
            }
        }
        static void Main(string[] args)
        {
            int[] Array1D = new int[3] { 1, 2, 3 };
            Print(Array1D);

            Console.WriteLine();

            int[,] Array2D = new int[2, 3] { { 2, 4, 6 }, { 8, 10, 12 } };
            Print(Array2D);
        }
    }
}


/*
run:
  
  1  2  3

  2  4  6
  8 10 12

*/

 



answered Aug 16, 2018 by avibootz
...