Unknown breaking change in .NET 4

Today I ran into a breaking change in .NET 4 which I couldn’t find in the documentation. It’s about binding a linq to objects query to a BindingSource’s DataSource in winforms. The code works properly in .NET 3.5, but crashes in .NET 4:

  1. _firstRelationshipsBindingSource.DataSource =
  2.                     from relationship in GuiStateSingleton.GetInstance().CurrentProject.
  3.                             GetAllRelationshipsForEntity(selectedEntity, true)
  4.                     where ((relationship.RelationshipType == EntityRelationshipType.ManyToOne) &&
  5.                             (relationship.EndVertex==selectedEntity)) ||
  6.                         ((relationship.RelationshipType == EntityRelationshipType.OneToMany) &&
  7.                             (relationship.StartVertex == selectedEntity))
  8.                     select relationship;

This binding source is bound to a simple winforms combo box. When the selection changes, I simply do:

  1. _relationshipOneViewer.ToView = (RelationshipEdge)_relationshipOneComboBox.SelectedItem;

This works, because the relationship viewer can handle ‘null’ values when there’s no selected item present. According to the query, the elements can be of type RelationshipEdge, the type of ‘relationship’ in the query.

In .NET 3.5, this works fine. If there are no elements returned by the query, this code will never hit, and even if it would, ToView would be set to null and everyone is happy. In .NET 4, it’s a different story: SelectedItem is set to a value even if there are no elements in the linq to objects query, namely aWhereEnumerableIterator instance. It works OK if the query returns values, but when the query is empty, the WhereEnumerableIterator instance is ending up as the ‘selected’ item, causing the cast to go wrong.

It’s easy to fix this of course: append a .ToList() to the query or use ‘as’ instead of the cast. The problem is that this issue is never going to pop up in previous .NET versions, so in general developers won’t think about this.

I don’t know whether this is a bug in .NET 4 or a breaking change. I can’t think of a reason why one wouldchange the .NET framework for this reason, so it looks like a bug. Either way, the only way to get rid of it is to work around it, as Microsoft isn’t shipping fixes on a regular basis.

UPDATE: When I add a .ToList(), the code works as expected, so the issue isn’t in BindingSource but in the enumerator.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s