Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the underlying reason this == comparison fails? (surprising result for me)

Context: I am prototyping in prep for (maybe) converting my WinForms app to WPF.

I make very simple tree view event handler for which the code is:

var treeViewItem = (TreeViewItem)e.NewValue;
var treeViewItemTag = treeViewItem.Tag;
if (treeViewItemTag == "ViewForAMs")
{
    ObjectQuery<AccountManagerView> oq = entities.AccountManagerViews;
    var q =
        from c in oq
        select c;
    dataGrid1.ItemsSource = q.ToList();
}

and the XAML is:

<Window x:Class="AccountingWpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <DockPanel>
        <TreeView Name="treeView1" ItemsSource="{Binding Folders}"
          SelectedItemChanged="treeView1_SelectedItemChanged">
            <TreeViewItem Header="Account Manager View" Tag="ViewForAMs"/>
        </TreeView>
        <DataGrid AutoGenerateColumns="True" Name="dataGrid1" />
    </DockPanel>
</Window>

When I ran it, I fully expected to see my data grid get populated but the == comparison failed on the second line of code above.

The debugger shows this:

QUESTION: why were there no compile or runtime errors? (same question another way: what is actually being compared such that the == operator outputs FALSE?)

enter image description here

like image 868
Aaron Anodide Avatar asked Apr 25 '11 18:04

Aaron Anodide


3 Answers

Cast the Tag to string first. In the default implementation on object, == compares references. As the Tag property is of type object, it is using the lowest common == operator between object and string, which is the object implementation. By casting Tag to string, the implementation on string is used, which is a value comparision.

like image 98
Femaref Avatar answered Oct 14 '22 10:10

Femaref


Use Object.Equals(treeViewItemTag, "ViewForAMs") instead

like image 4
Naveed Ahmad Avatar answered Oct 14 '22 09:10

Naveed Ahmad


If you look at the type of treeViewItemTag, you will see that the type is object, not string. So when you use ==, you are comparing the references of two objects. That will always return false in this case. If you use Equals() instead, or cast to a string, then it should work.

like image 2
Phil Avatar answered Oct 14 '22 09:10

Phil