You are here:

C#/Fixing a method when is called

Advertisement


Question
Hello Murat,

I want to convert a program wrote in C++ to visual C Sharp. This program compare two rows of a matrix (2x5)

to see if they match. But when the method ArrayCompare is called i got some errors could you help me, thanks.

This is the program:

private void button1_Click(object sender, EventArgs e)
{
   bool rowMatch = false;
   int numelements = 5;

   int[,] myArray = new int[2, 5] {{ 02, 15, 18, 20, 39 },
         { 07, 11, 14, 15, 34 }};

   listBox1.Items.Clear();

   // First it is displayed the array
   for (int i = 0; i < 2; i++)
   {
       string row = i + 1 + " )   ";

       for (int j = 0; j < 5; j++)
       {
         row += myArray[i, j] + "     ";
       }
       listBox1.Items.Add(row);
   }
   // It is compared myArray's two rows

   for (int i = 0; i < 2; i++)
   {
       for (int j = i + 1; j < 5; j++)
       {
         // When the method ArrayCompare is called i got some errors

         if (ArrayCompare(ref myArray[i], ref  myArray[j], ref numelements) == true)
         {
         rowMatch = true;
         }   
       }
    }   
    if (rowMatch)
    {
        listBox1.Items.Add(" ");
        listBox1.Items.Add("Rows Match");
    }
    else
    {
        listBox1.Items.Add(" ");
        listBox1.Items.Add("Rows No Match");
    }
}  
// This is the method that compare the two rows of myArray

bool ArrayCompare(ref int[] first, ref int[] second, ref int numelements)
{
   for (int i = 0; i < numelements; i++)
   {
       if (first[i] != second[i])
       return false;
   }
   return true;
}

Answer
Hi there,

You have to modify your code slightly. Since in C# you cannot split dimensions the way you do in C++, change your ArrayCompare method as following:

static bool ArrayCompare(ref int[,] array, int firstDimensionIndex, int secondDimensionIndex, ref int numelements)
{
  for (int i = 0; i < numelements; i++)
  {
      if (array[firstDimensionIndex,i] != array[secondDimensionIndex,i])
      return false;
  }
  return true;
}
   }
}


and call it like this


if (ArrayCompare(ref myArray, 0, 1, ref numelements) == true)
        {
        rowMatch = true;
        }


Hope that helps,

Murat

C#

All Answers


Answers by Expert:


Ask Experts

Volunteer


Murat Mehmet

Expertise

I can help with questions about desktop and web programming in C#, including SOAP, XML, database managing, custom controls, security etc.

Experience

I have been developing web and especially desktop applications in C# and VB.Net for almost 5 years. My programming life has begun with VB6 long time ago, so its about 8 years that I am in this business.

Organizations
Was in R & D for 2 years in a popular Turkish technology website: cyber-warrior.com

Education/Credentials
2011 Computer Engineering graduation in University of Trakia in Turkey.

©2016 About.com. All rights reserved.