|
-
May 6th, 2013, 07:02 AM
#1
[RESOLVED] Problems with Action Delegates
I have a form with a button and the following code:
vb.net Code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dt As New DataTable
dt.Columns.Add("CustomerId", GetType(Integer))
dt.Columns.Add("Rate", GetType(Integer))
For i = 0 To 9
dt.Rows.Add(i, 0)
Next
Dim dataRows = dt.Rows.Cast(Of DataRow)().ToList
dataRows.ForEach(AddressOf SetRate) '<-- this works
' dataRows.ForEach(Function(dr) dr("Rate") = 9999) '<-- this doesn't work!
For Each dr In dt.Rows
Console.WriteLine(dr("CustomerId") & " " & dr("Rate"))
Next
End Sub
Sub SetRate(ByVal dr As DataRow)
dr("Rate") = 9999
End Sub
End Class
Output in when I do: dataRows.ForEach(AddressOf SetRate)
Code:
0 9999
1 9999
2 9999
3 9999
4 9999
5 9999
6 9999
7 9999
8 9999
9 9999
Output when I do: dataRows.ForEach(Function(dr) dr("Rate") = 9999)
Code:
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
I was assuming both the codes are equivalents, but they don't seem to be so. Though there are no compilation errors, the inline-function way doesn't work.
Anyone knows the reason why? Is it because the lambda expressions are evaluated when they are first used? Or is there any other reason?
-
May 6th, 2013, 08:33 AM
#2
Re: Problems with Action Delegates
Um, that second code snippet is not doing anything like what you think it is. I think that you need to brush up on how lambdas work; especially the difference between action lambdas (which do not exist in VB 2008) and value lambdas. A lambda is a contraction of a conventional method. This lambda:
Code:
Function(dr) dr("Rate") = 9999
is equivalent to this conventional method:
Code:
Private Function Method(ByVal dr As DataRow) As Boolean
Return dr("Rate") = 9999
End Function
Your code is not setting anything. It's determining whether a field is equal to a particular value.
If you take nothing else from this, turn Option Strict On right now and never turn it Off again unless you explicitly need late-binding for Office Automation or the like and, even then, only do so in partial classes where it's absolutely required. Your code wouldn;t even compile with Option Strict On and that would be a good thing.
-
May 7th, 2013, 02:34 AM
#3
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|