Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to c#. Struggling with printing Array values. Throwing error "not all code paths return a value". Pls help me. Below is the code. Im calling this class from aspx file. Want to print in my web page. Thanks in advance.
C#
public class ArrayExample
{
    int[,] myTable = new int[2, 3];
    public ArrayExample()
	{
		//
		// TODO: Add constructor logic here
		//
        myTable[0, 0] = 1;
        myTable[0, 1] = 2;
        myTable[0, 2] = 3;
        myTable[1, 0] = 4;
        myTable[1, 1] = 5;
        myTable[1, 2] = 6;
	}
    public int CallArray()
    {
        for (int row = 0; row < myTable.GetLength(0); row++)
        {
            for (int col = 0; col < myTable.GetLength(1); col++)
            {
                return myTable[row,col];
                
            }
        }
    }

}


Im calling this class from by Aspx.cs file.

C#
protected void btnArray_Click(object sender, EventArgs e)
   {
       ArrayExample aex = new ArrayExample();
       Response.Write(aex.CallArray());
   }

i want to print this in array format in my web page
Posted
Updated 29-Dec-12 17:45pm
v2

1 solution

The reason for this compiler error is what if myTable.Legth returns zero? program execution will not go inside the loop and its not possible to know what value to return.

change your code like below
C#
public int CallArray()
 {
     for (int row = 0; row < myTable.GetLength(0); row++)
     {
         for (int col = 0; col < myTable.GetLength(1); col++)
         {
             return myTable[row,col];

         }
     }
return -1;// you can treat this as error condition or array is empty 
 }
 
Share this answer
 
Comments
BalajiJayaram 29-Dec-12 23:37pm    
Thank for your reply Jibesh. Its printing the first value of array myTable[0,0]. But i want to print all values in the array format. Pls suggest me the right code. Thanks
Jibesh 29-Dec-12 23:41pm    
Ofcourse yes. because you are exiting from the loop for the first iteration itself, to print all the line you need to call the print method inside the loop. can you copy your print code too.
BalajiJayaram 29-Dec-12 23:46pm    
Updated my print code. pls do the needful

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900