If you read the instructions carefully, you have this requirement:
...includes a method that accepts any number of words...
You accomplish this by using the params
keyword along with a string[]
.
...and sorts them in alphabetical order.
This part you doing with Array.Sort(newWords);
Demonstrate that the program works correctly when the method is called with one, two, five, or ten words
This part you're not doing - you're assuming in your code that the input array will have 10 items, when instead you should check to see how many items it has before outputting the results.
Since the array size cannot be determined by the method, then it cannot make any assumption that there will be enough labels on the form to populate with the results. Given this, we could use a MessageBox
to show the results instead, and we can use String.Join
to join all the items in the array with an Environment.NewLine
character in order to show the sorted words in different lines:
private void SortAndPrint(params string[] newWords)
{
Array.Sort(newWords);
MessageBox.Show(string.Join(Environment.NewLine, newWords));
}
Now, we can demonstrate the use of this function by passing in different numbers of arguments to it.
First, just so we're on the same page, I have this code in the Form_Load
method that adds 10 textboxes to the form, all with the tag "input":
private void Form1_Load(object sender, EventArgs e)
{
var stdHeight = 20;
var stdWidth = 100;
var stdPad = 10;
var count = 10;
for (int i = 0; i < count; i++)
{
var textBox = new TextBox
{
Name = "textBox" + (i + 1),
Left = stdPad,
Width = stdWidth,
Height = stdHeight,
Top = (stdHeight + stdPad) * i + stdPad,
Tag = "input"
};
Controls.Add(textBox);
}
}
Now, in our button click event, we can search for all controls on the form who have the Tag == "input"
and whose .Text
property is not empty, and we can pass these Text
values to our method both as a single array OR as individual items:
private void button1_Click(object sender, EventArgs e)
{
// Select all textbox Text fields that have some value
var words = Controls.Cast<Control>()
.Where(t => t.Tag == "input" && !string.IsNullOrWhiteSpace(t.Text))
.Select(t => t.Text)
.ToArray();
// Pass all the words in a single array to our method
SortAndPrint(words);
// We can also demonstrate this by passing individual words
// Pass one word if we can
if (words.Length > 0)
{
SortAndPrint(words[0]);
}
// Pass two words if we can
if (words.Length > 1)
{
SortAndPrint(words[0], words[1]);
}
// Pass five words if we can
if (words.Length > 4)
{
SortAndPrint(words[0], words[1], words[2], words[3], words[4]);
}
// Pass ten words if we can
if (words.Length > 9)
{
SortAndPrint(words[0], words[1], words[2], words[3], words[4],
words[5], words[6], words[7], words[8], words[9]);
}
}