Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27215

VS 2008 Problems with Action Delegates

$
0
0
I have a form with a button and the following code:
vb.net Code:
  1. Public Class Form1
  2.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  3.         Dim dt As New DataTable
  4.         dt.Columns.Add("CustomerId", GetType(Integer))
  5.         dt.Columns.Add("Rate", GetType(Integer))
  6.         For i = 0 To 9
  7.             dt.Rows.Add(i, 0)
  8.         Next
  9.  
  10.         Dim dataRows = dt.Rows.Cast(Of DataRow)().ToList
  11.         dataRows.ForEach(AddressOf SetRate)                 '<-- this works
  12.         ' dataRows.ForEach(Function(dr) dr("Rate") = 9999)    '<-- this doesn't work!
  13.         For Each dr In dt.Rows
  14.             Console.WriteLine(dr("CustomerId") & "     " & dr("Rate"))
  15.         Next
  16.     End Sub
  17.  
  18.     Sub SetRate(ByVal dr As DataRow)
  19.         dr("Rate") = 9999
  20.     End Sub
  21. 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?

Viewing all articles
Browse latest Browse all 27215

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>