Welcome to MSDN Blogs Sign in | Join | Help

jaredpar's WebLog

Code, rants and ramblings of a programmer.

Syndication

News

Now Reading

Expert F#

What's a better book to read when learning F#?

Essential WPF

Thus far the best book I've read on WPF. Gets right down to working with WPF and the goals/history.

Purely Functional Data Structures

Reading this book makes me feel like I'm back in college. It will really get your mind going and is best read with a whiteboard handy.

Blog Roll

Eric Lippert
Dustin Campbell
Jon Skeet
Coding Horror
Brian McNamara
Brian Bondy
Hub FS
Full List

Type Inference and IEnumerable

This is somewhat of a follow up on a previous post I did on the difference between IEnumerable(Of T) and the IEnumerable interfaces. 

I've seen several people type in the following code and wonder if there was a fundamental bug in the type inference code.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each cur In Controls
            cur.Text = "A Value"
        Next
    End Sub

This code will produce an error stating that "Text" is not a member of object.  Users expected type inference to type the variable "cur" as Control.  Unfortunately this is "By Design". 

Much of the original .Net Framework was written before the CLR implemented support for generics.  As a result all of the collection classes were loosely typed to Object by implementing IEnumerable.  So in this case type inference will correctly type this as Object.

There are 2 ways to fix this problem.

  1. Explicitly type the For Each variable to be the actual type of objects in the collection
  2. Use a Shim to change the type of the collection. (see http://blogs.msdn.com/jaredpar/archive/2007/10/04/ienumerable-and-ienumerable-of-t.aspx)

Published Monday, November 26, 2007 5:32 PM by Jared Parsons

Comments

# Understanding LINQ @ Wednesday, December 05, 2007 8:24 PM

Note : I plan to post this blog on the VB team blog eventually. However, because of the length and complexity,

Tim Ng

# Understanding LINQ @ Wednesday, December 05, 2007 9:23 PM

Note : I plan to post this blog on the VB team blog eventually. However, because of the length and complexity

Noticias externas

New Comments to this post are disabled
Page view tracker