views:

35

answers:

2

I've got this nifty little piece of code here that self-propogates ad infinitum every time the relevant method is called:

if (this.ListBox_MyListBox.Items[e.Index] is MyObject)
                    {
                        MyObject epicObject= new MyObject();
                        epicObject= (MyObject)this.ListBox_MyListBox.Items[e.Index];
                        epicObject.Name = epicObject.Name + " (label)";

The method in question is a click event, and unfortunately, every time I click, it adds another " (label)" to the end of the name string.

Elsewhere, I have a very similar situation which doesn't need a cast

if (this.ListBox_MyListBox.Items[e.Index] is String)
                    {
    string tag = (string)this.ListBox_SmartSetOptions.Items[e.Index]+ " (tag)";

and that code works fine.

I had thought that declaring a new object each time would avoid the endless repetition, but its still happening. What am I missing?

+3  A: 

If you only want to append " (label)" once, you can do something like this:

if (!epicObject.Name.EndsWith(" (label)"))
{
    epicObject.Name += " (label)";
}

Is that what you're trying to do?

When you append " (label)" to the .Name property, the .Name property is replaced by the new string you're creating with " (label)" at the end.

Jon B
+1, yes, I had thought of this myself, but was hoping to do so in a way that avoided parsing the name property each time.
Raven Dreamer
A: 

This code looks awfully strange to me, I think you're trying to do something more like

if (this.ListBox_MyListBox.Items[e.Index] is MyObject) 
                { 
                    epicObject.Name = ((MyObject)this.ListBox_MyListBox.Items[e.Index]).Name + " (label)"; 

The reason you're getting the appendage in the ListBox is because you set epicObject to the item in the ListBox which is actually making it a reference to the object, and then altering the Name property on epicObject alters the name property of what it references - the item in the ListBox. The code I listed above just sets your epicObject.name to the selected name + " (label)"; not altering the listbox item.

Jimmy Hoffa