Reputation: 707
I'm sorting the lines of a text box in reverse alphabetical order, and the code I have works fine:
string[] temp = textBox.Lines;
Array.Sort(temp);
Array.Reverse(temp);
textBox.Lines = temp;
But I'm confused as to why Visual Studio wouldn't let me do:
Array.Sort(textBox.Lines);
Array.Reverse(textBox.Lines);
Mostly I'm trying to figure out the subtleties of C# since I'm still new to it.
EDIT: The second snippet doesn't error out, but it doesn't execute any code (i.e. doesn't appear to do anything).
Upvotes: 1
Views: 112
Reputation: 66439
Here's a few lines of the getter for TextBox.Lines
:
public string[] Lines
{
get
{
string text = Text;
ArrayList list = new ArrayList();
...
...
return(string[]) list.ToArray(typeof(string));
}
You're getting a new collection, which has a copy of the data in it from the TextBox
. You're not actually sorting the data in the TextBox
.
When void Array.Sort
is done sorting the array passed back from that property, the original TextBox
remains unchanged.
Upvotes: 3
Reputation: 73442
Indeed, your array will be sorted and reversed, but what happens is that will not be assigned to TextBox
. Modifying the Lines
array has no effect since it is computed property.
You need to assign it to Lines
property to see the effect.
Here is the reference to source
Upvotes: 2
Reputation: 8551
This is because textBox.Lines is not exposed as a member variable on the class but rather as a property. Behind the scenes, a property is really two methods, e.g. get_Lines and set_Lines. All you know about the array you get back from get_Lines is that it's an array of strings. There's no guarantee that that property is backed by an actual array--maybe TextBox keeps the text internally as one big string that it then breaks into pieces for you when you call get_Lines. So you're not necessarily modifying the internal list when you call Sort() and Reverse() on the result of get_Lines.
Upvotes: 0