How to do iterators in vb.net?
-
venerdì 21 gennaio 2011 11:22
How can i write this in vb.net? also there is not example on ivalidatableobject at all in the library..<br/>public class SomeModel : IValidatableObject { public int PropertyOne { get; set; } public int PropertyTwo { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (PropertyOne <= PropertyTwo) { yield return new ValidationResult( "PropertyOne must be larger than PropertyTwo"); } } }
Tutte le risposte
-
venerdì 21 gennaio 2011 15:32
Unfortunately, this is one of the few features in C# which has no direct VB equivalent.
You have to track what you need to return and roll your own iterator logic - someone else may have a good example of how to do this.
Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com) -
venerdì 21 gennaio 2011 16:18
Hi,
This is not yet available in VB. In this particular example I don't see why it is usefull, just return the value as a list with a single element without using yield (this is mostlty usefull for huge lists when you want to return each element in turn when needed rather than all at once) i.e.
Public Function Validate() As IEnumerable(Of ValidationResult) Return {New ValidationResult("Goobye World !")} End FunctionThe {} notation just allows to "embed" this ValidationResult in an array (as an array is enumerable).
It should be available in a later version with more general async programming features. See http://blogs.msdn.com/b/vbteam/archive/2010/10/28/async.aspx (Announcing the Async CTP for VB with iterators too).
Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".- Modificato Patrice ScribeMVP venerdì 21 gennaio 2011 16:26 Misleading formulation changed and code included
- Proposto come risposta RoninB venerdì 21 gennaio 2011 17:07
- Proposta come risposta annullata Se3ker sabato 22 gennaio 2011 10:28
-
venerdì 21 gennaio 2011 16:22Ive had async ctp installed but kept crashing so i uninstalled it. Anyway ive tried everything, returning values regulary but its always the wrong type or some kind of error.
-
venerdì 21 gennaio 2011 16:30Sorry for the late update ;-) The CTP was to inform about future changes. Meanwhile I updated my earlier post with some code as I realized my first suggestion wasn't that clear...
Please always mark whatever response solved your issue so that the thread is properly marked as "Answered". -
venerdì 21 gennaio 2011 17:02
If PropertyOne <= PropertyTwo
return "PropertyOne must be larger than PropertyTwo"
End if
You're welcome :)
Adam
Ctrl+Z -
venerdì 21 gennaio 2011 17:05
Note that if "yield return" was required in C# and not simply a mistake, then a simple "Return" in VB certainly won't cut it.
If "Return" looks like the right answer, then either the original C# code is wrong or you don't understand iterators.
Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)- Proposto come risposta Rudedog2MVP venerdì 21 gennaio 2011 22:56
- Contrassegnato come risposta Se3ker sabato 22 gennaio 2011 13:01
-
venerdì 21 gennaio 2011 22:56
Note that if "yield return" was required in C# and not simply a mistake, then a simple "Return" in VB certainly won't cut it.
If "Return" looks like the right answer, then either the original C# code is wrong or you don't understand iterators.
Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
Bingo!
I guess the problem is the C# contextual keyword, yield. It is not a keyword in the classic sense. Contextual keywords are used to give special meaning to the code, which may or may not directly result in compiled code. The VB keyword Partial is an example of a contextual keyword that does not directly lead to compiled code. The Property keyword is an example of a contextual keyword that does directly lead to compiled code. Property causes methods to be generated in IL.
The "Yield" keyword tells the compiler that the defining method is a special method known as an iterator block. An iterator block is a block of code that returns members of a collection. The yield keyword causes the compiler to generate a special nested class that implements behavior based upon the context of how the keyword is used. The special behavior is best described as a state machine.
A state machine method is one that is designed to be called repeatedly with the same input data, but returns a different result each time. In this case, the iterator block state machine returns a special type instance that represents a member of a collection. The yield keyword is used to identify the value or object instance that is to be returned from the iterator block.
The following link describes how to implement iterator blocks in Visual Basic.
http://msdn.microsoft.com/en-us/vstudio/gg497937 Iterators in Visual Basic
This links shows you how to implement the generic interface IEnumerable(Of T) in VB.
http://msdn.microsoft.com/en-us/library/dd145423.aspx Walkthrough: Implementing IEnumerable(Of T) in Visual Basic
http://www.codeproject.com/KB/architecture/Iterator_Pattern.aspx The Iterator Pattern - VB Sample
As for your code C# sample, it is not making much sense. The context is not right. Surprisingly, it does not throw a compiler error because the keyword does not appear within a foreach block. Aside from that minor mystery, I would almost say that the yield keyword is not needed. The method parameter is not even used either. The return object is supposed to be a collection, which I assume means that ValidationResult is a type that can be cast to the method's return type.
However, if the following class is called in the yield statement, it still compiles, no throw no run time errors. I would almost say that the yield keyword is not needed. Without yield, you get an invalid cast on the return type.
class ValidationResult
{
public ValidationResult(string message)
{
}
}
Like I already said, the context is not quite right. I cannot translate it. Not enough info to get it right. It almost appears as if you posted an abbreviated version of the original class definition. "Here, I need just this part done. I don't know how to do this part with the yield keyword. Please help me out with this method. I can handle the rest."
That's just the way it appears because the C# code is not making much sense on its' own. I cannot bring myself to believe that anyone knowledgeable enough to use the 'yield' keyword would write something that as twisted up as that is. For example, what type of collection is supposed to be returned when the IF condition evaluates as false? I believe that Iterators are not supposed to ever return a null. An exception should be thrown, instead.What type of collection is ValidationResult, whose constructor accepts a string parameter?
Rudy =8^D
Mark the best replies as answers. "Fooling computers since 1971."- Contrassegnato come risposta Se3ker sabato 22 gennaio 2011 13:01
-
sabato 22 gennaio 2011 10:41
Ok, this is interesting. Yet still no examples. ...vb.net is a forgoten language. :(
Anyway, create a poco and implement .net 4 ivalidatableobject
Im actually using asp.net mvc 3, which honors ivalidatableobject out of the box. All of the examples from Scott Guthrie, Phil Haack and the other are in c#, i thought this would be easily translatable to vb.net.
Public Class Screen Implements System.ComponentModel.DataAnnotations.IValidatableObject Public Function Validate(validationContext As System.ComponentModel.DataAnnotations.ValidationContext) As System.Collections.Generic.IEnumerable(Of System.ComponentModel.DataAnnotations.ValidationResult) Implements System.ComponentModel.DataAnnotations.IValidatableObject.Validate End Function End Class
-
sabato 22 gennaio 2011 12:25
Ok, this is interesting. Yet still no examples. ...vb.net is a forgoten language. :(
No samples? You must be joking. I guess you what really mean is that no one has posted an exact solution.I posted several links with samples including a link to the VB "Yield" keyword, which was designed to be the functional equivalent of the C# "yield" keyword. I even told you why it was not possible to post a translation. And now, you turn around and criticize those who are trying to help you.
Well, at least your provided context by telling us something about it. And then you post another problem, albeit similar. I will tell you where to take your problem with ASP.NET.
Rudy =8^D
Mark the best replies as answers. "Fooling computers since 1971." -
sabato 22 gennaio 2011 13:00
Im sorry, i ment there are no examples of ivalidatableobject in the msdn library. Thank you for the links to iterators, ive been aware of those, but at the moment i cant say i understand them.
I wasnt trying to criticise, i just thought there should be a simple translation for this problem. It though it would be more general, a simple syntax problem rather then a specific asp.net issue, couse ivalidatable isnt infact confined to just asp.net.
-
sabato 22 gennaio 2011 14:08
If you wish to emulate the C# yield keyword properly in VB, then you need to use the Iterator Pattern. See my link above. It means you need to create a class similar to the "BookEnumerator" class in the complete sample near the bottom of the page. the methods that you have posted are variations on the implementation of this method in the sample.
Public Function GetEnumerator() As System.Collections.IEnumerator _ Implements System.Collections.IEnumerable.GetEnumerator Return New BooksEnumerator(mList) End Function
If do not know what you are doing, please do not expect us to tutor you. We can try to answer your specific questions, but we are not able to be your personal tutor. You may need to learn some things about general programming before you proceed with an advanced topic such as MVC.
Just as learning a new spoken language does not teach one how to write a sophisticated document like a screenplay for a movie, simply learning a new computer language does not teach one how to write a sophisticated program with the MVC pattern as used in ASP.NET.
MVC is what is known as a sophisticated Design Pattern, which many developers have trouble understanding. Design Patterns are at the core of Object Oriented Programming. Difficulty with OOP is prevalent among VB programmers because it tends to go against the grain of what most VB developers like about the language. Most OOP code simply lacks the "plain English" readability that most VB code presents.
There are 23 basic Design Patterns created almost 2 decades ago by a group of four C developers, who are immortalized with the nickname "Gang of Four" or GoF for short. The MVC pattern is actually a pattern of a subset of the basic 23 patterns. Since that time, quite a number of these aggregate patterns have been created and documented.
The basic 23 patterns are divided into 3 categories, Creational, Structural, and Behavioral. The Iterator Pattern falls into the Behaviorial category.
Mark the best replies as answers. "Fooling computers since 1971." -
sabato 22 gennaio 2011 14:39
Let me correct myself, its not that i dont understand, also its not that i just started developing, its illogical to do a full enumerator just to return in my example a true/false. It just is.
Thanks for the history reminder but thats not relevant to my problem whatsoever.
Also you make it sound like all developers who code in vb.net are 3 year old children you just tried to tutor.
its not about readability of vb, i chose it primarily because some IDE enhancements it has were more productive, especially with last version you dont need to close all the time with () or in c# with ; you dont need _ you dont need to get; set; you dont need anything, also i thought it was a microsoft language. it seems that ill need to syntax my brain to C world to get treated like an adult.
Ive been on edge to switch last few months, thank you for confirming it for me, and nowhere less then in vb.net forum.
-
sabato 22 gennaio 2011 15:42
What I had just previously said went right over your head. I did not suggest that you go out and learn C++ or C#. I had simply suggested that you learn Design Patterns before you try to use one. Design Patterns can be applied in any of the .NET languages, including VB.NET. I am not here to debate the merits or demerits of VB.
It is a simple fact of life of why most VB developers have more difficulty with learning OOP compared to other languages. It goes against the grain of what makes them prefer VB. OOP code written in VB lacks the classic readability that has been the hallmark of all versions of BASIC. Maybe, just maybe, that is why you are finding difficult to find examples written in VB.
There are simply not as many people are doing OOP in VB.NET as compared to other languages. But, they are out there. You just have to work harder to find the VB examples. Or maybe, just maybe, there is little or no difference between VB.NET and C#. There is a much more significant difference between Visual Basic and C#.
ASP.NET MVC 3: The Official Microsoft ASP.NET Site
You see, I happen to think there is a significant difference between programming in Visual Basic and progamming VB.NET. Contrary to appearances, they are not the same. Not even close. This difference is the obstacle that you currently face, not me or anyone else. Visual Basic is really just a wrapper around VB.NET. Many features of VB such as the "My namespace" and other VB specific features are merely wrappers around types and method calls available in the .NET Framework Class Library.
If you feel that writing an enumerator class for your custom collections is too much work, then that is your choice. There is only one thing left for me to say. There is no substitute for thorough programming. I would prefer to write something out myself than depend upon an ever-evolving compiler to write it for me. There are many C# programmers who write their own custom enumerator classes so that you iterate their custom collections in custom ways. The 'yield' keyword generates code that falls short of their needs.
Look at it this way. Using the 'yield' keyword is like designing a form with the Form Designer. If you wish to have complex forms, you abandon the designer and code it yourself. If programming shortcuts is what you seek, then stick to Visual Basic. If writing sophisticated programs is your goal, then learn VB.NET.
Happy coding.
Rudy =8^D
Mark the best replies as answers. "Fooling computers since 1971." -
sabato 22 gennaio 2011 16:36
http://www.dofactory.com/Framework/Framework.aspx
That package is the best documentation of the 23 basic GoF Design Patterns. Look at it as purchasing a good book because it is. It comes with an e-bbok that explains all of the patterns in detail. The asking price is a bargain.
Mark the best replies as answers. "Fooling computers since 1971." -
domenica 23 gennaio 2011 20:16"Se3ker" wrote in message news:46861b11-ea67-4c34-9fa7-97161a6228f8...
How can i write this in vb.net? also there is not example on ivalidatableobject at all in the library..
<br/>public class SomeModel : IValidatableObject { public int PropertyOne { get; set; } public int PropertyTwo { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (PropertyOne <= PropertyTwo) { yield return new ValidationResult( "PropertyOne must be larger than PropertyTwo"); } } }
The Yield keyword is available in VB.Net. Have a look at : http://msdn.microsoft.com/en-us/gg497937
Iterators in Visual Basic
An iterator in Visual Basic can be used to step through collections such as lists and arrays.
An iterator function or get accessor performs a custom iteration over a collection. An iterator function uses the Yield statement to return each element in turn. When a Yield statement is reached, the current location is remembered. Execution is restarted from that location the next time the iterator function is called.
The return type of an iterator function or get accessor can be IEnumerable,IEnumerable(T), IEnumerator, or IEnumerator(T). An Iterator modifier is included in the function or get accessor declaration.
An Exit Function or Return statement can be used to end the iteration. They are the equivalent of a yield break statement in C#.
Note: Iterators were introduced in C# in Visual Studio 2005. For more information, see Iterators (C# Programming Guide).
Simple Iterators
The following Visual Basic example includes multiple Yield statements. Each iteration of the For Each statement body creates a call to the iterator function, which goes to the next Yield statement.
Sub Main() For Each number As Integer In SomeNumbers() Console.Write(number & " ") Next ' Output: 3 5 8 Console.ReadKey() End Sub Private Iterator Function SomeNumbers() As IEnumerable ' Use multiple yield statements. Yield 3 Yield 5 Yield 8 End Function
Harry- Proposto come risposta JBKmsdnMVP giovedì 26 gennaio 2012 21:51
- Proposta come risposta annullata JBKmsdnMVP giovedì 26 gennaio 2012 21:52
-
giovedì 26 gennaio 2012 22:03
My recent two-part article series in Visual Studio Magazine covers iterators specifically for Visual Basic .Net. I tried hard to provide realistic and useful examples of iterator use. I believe you will find the explanations and the examples very helpful.
The two articles are:
1. Understanding Iterators: Concepts, Benefits and Functionality
http://visualstudiomagazine.com/articles/2011/11/10/understanding-iterators-part-1.aspx2. Understanding Iterators, Part 2
http://visualstudiomagazine.com/articles/2012/01/06/understanding-iterators-part-2.aspxGood Luck
Joe Kunk
Microsoft MVP Visual Basic
Visual Studio Magazine On VB columnist
Joe Kunk -
domenica 8 aprile 2012 17:53
public class SomeModel : IValidatableObject { public int PropertyOne { get; set; } public int PropertyTwo { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (PropertyOne <= PropertyTwo) { yield return new ValidationResult( "PropertyOne must be larger than PropertyTwo"); } } }Public Class SomeModel Implements IValidatableObject Public Property PropertyOne As Integer Public Property PropertyTwo As Integer Public Function Validate(validationContext As System.ComponentModel.DataAnnotations.ValidationContext) As System.Collections.Generic.IEnumerable(Of System.ComponentModel.DataAnnotations.ValidationResult) Implements System.ComponentModel.DataAnnotations.IValidatableObject.Validate If PropertyOne < PropertyTwo Then Return {New ValidationResult("some message")} Else Dim dummy As IEnumerable(Of ValidationResult) = {} Return dummy End If End Function End Class

