To streamline code, I increasingly rely on lambda expressions. But I may have hit against the wall in the attempt of removing an event handler set by a lambda expression. This really eludes me. The code below shows two samples: Alt1 uses a plain lambda expression as delegate and works fine: the object size increases as the numeric control varies. However, the drawback is that the handler cannot be removed:
RemoveHandler Me.upDnScale.ValueChanged, Sub(sender As Object, e As Object) ScaleObject1(sender, e, objTgt)
According to this MSDN article, a variable should be used to set/remove lambda based handlers. Alt2 shows a couple of attempts, but none works.
I see lambda expressions have become a very useful tool at some points in the language. I've been using them a lot and most of the time they fit really nice and make the code shorter and perhaps clearer.
Now.. I've seen some , I would say excessive use of them. Some people like them so much that try to use them everywhere they can.. Some times the C# code looks like a functional language. Other factors against are the cost using reflection by lambda and that not friendly to debugging.I would like to hear opinions about how good and how code clear it is to use more or less the lambda expressions. (this is not the better example, but let's say it was the trigger)I was writing the following code. The use of the delegate { return null; } helps me avoid having to ask if the event is null or not every time I have to use it.
public delegate ContactCellInfo.Guest AddGuest(); public event AddGuest GuestRequest = delegate { return null;}
Im using resharper and the wise resharper( even it some times literaly eats the memory) made me the following suggestion
public delegate ContactCellInfo.Guest AddGuest(); public event AddGuest GuestRequest = () => null;
At my point of view the code using the delegate looks clearer. I am not against the Lamdba expression just would like to hear some advices on how and when to use them.
Functionally, is there any difference (apart from syntax onbviously) between lambda expressions in C# and VB.Net?EDIT: following up on CraigTP's answer: any references to the situation in .Net 4?EDIT: I'm asking because I'm used to C#, but for a next project the customer asks VB.Net. We're not a priori against that. We realize that most language constructs are supported in both languages. However, we're particularly fond of the way C# implements lambda expressions. We would like to have an overview of the differences with VB.Net
EDIT: accepted CraigTP's answer for pointing out what I currently consider the most important difference.
So to summarize: VB.Net 9 does not support multiline statements in a lambda expression, and a lambda must always return a value. Both of these issues are addressed in VB.Net 10
Async Sub like this: Dim f As Func(Of Task) = Async Sub() End Sub Produces compiler error: error BC36670: Nested sub does not have a signature that is compatible with delegate 'System.Func(Of System.Threading.Tasks.Task)'.Equivalent C# code compiles fine:
Func<Task> f = async () => { };Rewriting Async Sub into Async Function make code works.
Why does Async Sub() is not convertible to delegate types with return value of type Task?
I have a List(of T) where T has a property that is a list of checkboxes, what I need is a Lambda expression that will count all the checked checkboxes in the list. I tried with:
I just came across a bug in NHibernate which happens to already be raised: [url] I'm not sure if this applies to anything else other than enums but when using a Lambda from VB, it looks different to the same Lambda from C#.
They are the same as far as I'm aware? (My VB isn't great) If I put a break point on the same line of code, where the above code is passed into. In C# I get: On the same line when VB version is passed in, I get: Is this something I'm doing wrong? Is the result's the same, just displayed different between C#/VB?
Edit: Ok so they are displayed different, but they can't be the same because NHibernate cannot handle it. The C# version is handled perfectly fine by NHibernate, the VB version resolves in the following exception being thrown: [Code]
I'm trying to expand my programming horizons, and LINQ and Lambda Expressions have popped up as some apparently very important topics. As I began reading articles on Lambda Expressions, it appears that Lambda Expressions are built heavily on the concept of Delegates. As I began reading articles on Delegates, it appears that Delegates are built heavily on the concept of callback functions. As I began reading articles on callback functions, .[code]Can anyone out there give me a simple, clear, concise definition of callback functions? Do I need to learn C or C++ to fully understand these concepts? Maybe a better question is: What do I need to know to be able to understand Delegates (they've always somewhat mystified me) and LINQ/Lambda Expressions (I haven't looked into these too much, but they're mystifying, too)?I don't mind doing research, but google searches are giving me way too much information.
I have a type lets call it "MyType". I have a List(Of MyType). Here is what i'm doing: MyList.Sum(Function(x) x.MyFieldToTotal) "MyFieldToTotal" is a decimal. For the life of me i can't figure out why x above is an object rather than a type of "MyType". Shouldn't Type Inferencing be working in this case? Even in intellisense i get "selector as System.Func(Of MyType) as Decimal"
Currently I am searching through my list to find Customers that match on Address. I need to match on both address and city. How do I rewrite my lambda Expression to match both criteria?
How to remove a handler set up by a lambda expression? According to this MSDN article, lambda expression should be assigned to variables which should be used to define handler operators. So far, I have used lambda expessions w/o variables.
For instance, the following works: Private Sub ScaleObjectInit1(ByVal objSrc As NumericUpDown, ByVal objTgt As FrameworkElement) ... AddHandler Me.upDnScale.ValueChanged, Sub (sender As Object, e As Object) ScaleObject1 (sender, e, objTgt) End Sub Private Sub ScaleObject1(ByVal sender As Object, ByVal e As Object, ByVal objTgt As FrameworkElement) [Code] .....
Can someone who is using a 64 bit machine help me pintpoint this crash to either the VS2010 IDE itself or one of the plugins I have installed?
It's the code fragment below. When I copy & paste it into the Main() function of a new VB.Net console app on my Win7 64 bit machine, the VS IDE crashes and dies onthe spot, every time I try it.
Doing exactly the same on a 32 bit XP machine, nothing abnormal happens.
The 64 bit machine does have some IDE plug-ins installed, the biggest of which is DevExpress (the free version), so i think either one of those or the fact that the IDE is running on 64 bit must be the culprit.
This is the code. The static variable can also be made a module-level variable, with the same result.
I'm still trying to get my head around the whole "Lambda Expressions" thing.
Can anyone here give me an example ordering by multiple columns using VB.Net and Linq-to-SQL using a lambda expression?
Here is my existing code, which returns an ordered list using a single-column to order the results:
Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).ToList
Note: The WebCategory object has a child WebPage object (based on a foreign key). I'd like to order by WebPage.DisplayOrder first, then by WebCategory.DisplayOrder.
I tried chaining the order bys, like below, and though it compiled and ran, it didn't seem to return the data in the order I wanted.
Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).OrderBy(Function(c As WebCategory) c.WebPage.DisplayOrder).ToList
I have an untyped dataset returned from my WebService. The user wants to dynamically construct a query referencing tables and columns and specifying values to test for.I have looked at Lambda Expressions and the Expressions.Expression Namespace. I think these provide the answer I'm looking for, but I'm not certain how to go about contructing the linq expressions to extract the datarows I'm looking for.
I plan on limiting the result to one datatable that the query will result in and i"ll provide the joins from the user's constructs.For a simple example I have a DataTable with (n) rows called "Table", and in it there is a computed column called "b_IsActive" that has the expression "Convert(IsActive, 'System.Boolean')". The user wants to retrieve all rows in "Table" where field "b_IsActive" is true.
I'm looking for an advanced level VB.NET book which covers LINQ and Lambda Expressions.Generally I read C# .NET books due to lack of good VB.NET books when it comes to generic .NET Framework related subjects. However Lambda and LINQ is quite different in C# and VB.NET I'm looking for an advanced level VB.NET book on this subjec
Is it possible to shorten the following function to a lambda expression?Or (to do the trick by myself) what is the best and most understandable for beginners tutorial for lambda in vb.net?[code]
I've been wondering about lambda expressions for a while now.Consider the following code..[code]But in the lambda expression I have access to all Sub Main's variables.
Just switched over from VS2005 to VS2010 and I am having issues debugging my software. When I stop at a breakpoint, I can't see what variables contain. When I try to look at variables with QuickWatch, it states that it is "Unable to evaluate expression."
i'm coding a small app.i need to use regular expressions.I've got a huge string. and i need to find some substrings and put them into variables.for instance:<span class="(some constant class)">sb's Name</span> I need to cut "sb's Name" and put it into variable.how to do this using regular expressions?I know, that I can use webbrowser and whole DOM structure connected with it. But I can't, so I must use RegExp.
I'm getting my feet wet with Lambda expressions and it's rather overwhelming.I have a UserPrincipal object called SelectedUser. I wish to get a sorted list of the user's groups This is what I have so far but when I include that code my application's form flashes a few times and closes! Also, what is the significance of the "r" in the "Return From r" statement?
Dim SortedGroups As PrincipalSearchResult(Of Principal) = GetSortedGroups(Me.SelectedUser.GetGroups()) Private Function GetSortedGroups(ByVal psp As PrincipalSearchResult(Of Principal)) As PrincipalSearchResult(Of Principal) Return From r In psp.OrderBy(Function(t) t.Name) End Function
If I always need to call RemoveHandler after using AddHandler, where is the best place to do so? I have searched several similar questions as follows, but I do not quite understand.When and where to call the RemoveHandler in VB.NET? AddHandler/RemoveHandler Not Disposing Correctly..I thought garbage collection in c# or vb.net will take care of unused objects. Also, in vb.net designer, it automatically generates Dispose Sub. So I did not pay attention to programally releasing resource at all. Will I have any memory leak problems? Please kindly provide me some links/documents for me to start learning.[code]
I am working to a VB.NET windows forms projet in .NET 1.1. And I have this type of architecture, very simplified.[code]...
Depending of the type of test I am doing I create an instance of a specific test derived from BaseTestLogic. But I found that after hundreds of object creations I can have StackOverflow exception.
I checked my code and saw that I forgot to remove the handler to Timer Tick. The question is, where and when is it correct to remove hadler?
Do I need to implement the IDisposable interface in the base class and RemoveHandler in Dispose?
Using VB2008 Express I'm getting the following warning on a RemoveHandler statement and subsequent issues since the event is still hooked. Warning 1 The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler.
I'm getting a bit more fluent in VB.Net, but am still a bit green around the edges in certain aspects. I'm creating custom controls, and am starting to rely heavily on AddHandlers to manage them.Until recently, I didn't realize that you can add multiple event handlers for the same control and same address
[code]...
The above code would create 10,000 copies of the same event, and if I would click on combobutton1, the event would fire 10,000 times. I only need to fire the event once, but sometimes my code is a bit circular, and there may be an instance where two or more addhandlers are designated for a given control and address. Is there a way to have a loop on my custom dispose event where it would look something like:
[code]...
Or better yet, remove all events from a control(On a side note, is there any way in the debug mode to see all the active events attached to a control?)