Click here to Skip to main content
15,902,938 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do I define a public method that has an array in it?

I would like to set a method to public so it can be used with multiple button methods but the program says 'not all code paths return a value'. I assume that means I have not changed the 'void' value to the correct type but can anyone tell me what it is?

I have the following code:
C#
        public String bob ()
        {
        string [] averages = new string[2];
        averages[0] = value1.Text;
        averages[1] = value2.Text;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            bob();
            label1.Text = averages[1];

}

Thanks.

[Edit]Code block added[/Edit]
Posted
Updated 26-Mar-13 3:40am
v2
Comments
Sergey Alexandrovich Kryukov 26-Mar-13 13:39pm    
You cannot "call" an array. It is not a method, function, procedure, subroutine, property or operator.
—SA

Hi,

Change bob() into this:
C#
public String[] bob ()
       {
       string [] averages = new string[2];
       averages[0] = value1.Text;
       averages[1] = value2.Text;
       return averages;
       }

More about the return keyword:
http://msdn.microsoft.com/en-us/library/1h3swy84.aspx[^]
Hope this helps.
 
Share this answer
 
Comments
Ian A Davidson 26-Mar-13 12:24pm    
+5 for the answer. However, Member9941061 please note 1) you shouldn't need your method to be public, because you're calling it from a private method; 2) see Jeff's solution. Why do you need to construct an array of the values in your text boxes anyway, when you have direct access to them?
Why not just do this instead, since it's what you appear to be trying to do?

C#
private void button1_Click(object sender, EventArgs e)
{
   label1.Text = value2.Text;
}
 
Share this answer
 
C#
public string[] bob ()
{
    string [] averages = new string[2];
    averages[0] = value1.Text;
    averages[1] = value2.Text;
    return averages;
}

private void button1_Click(object sender, EventArgs e)
{
    string[] bobResult = bob();
    label1.Text = bobResult[1];
}


This is one solution to your question. The method "bob" returns string array. In the button1_Click method the result from "bob" call is assigned to variable with type string[] and name bobResult.
 
Share this answer
 
v2

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