views:

1953

answers:

4

In C#, when writing a function that returns an IEnumerble<>, you can use yield return to return a single item of the enumeration and yield break; to signify no remaining items. What is the VB.NET syntax for doing the same thing?

An example from the NerdDinner code:

public IEnumerable<RuleViolation> GetRuleViolations() {

   if (String.IsNullOrEmpty(Title))
       yield return new RuleViolation("Title required","Title");

   if (String.IsNullOrEmpty(Description))
       yield return new RuleViolation("Description required","Description");

   if (String.IsNullOrEmpty(HostedBy))
       yield return new RuleViolation("HostedBy required", "HostedBy");

   if (String.IsNullOrEmpty(Address))
       yield return new RuleViolation("Address required", "Address");

   if (String.IsNullOrEmpty(Country))
       yield return new RuleViolation("Country required", "Country");

   if (String.IsNullOrEmpty(ContactPhone))
       yield return new RuleViolation("Phone# required", "ContactPhone");

   if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
       yield return new RuleViolation("Phone# does not match country", "ContactPhone");

   yield break;
}

This convert C# to VB.NET tool gives a "YieldStatement is unsupported" error.

A: 

No yield return in VB.NET :( Just create a list and return it.

bbmud
+6  A: 

There is currently no equivalent to C#'s yield return in VB.Net from a language syntax level.

However there was a recent write up in MSDN magazine by Bill McCarthy on how to implement a similar pattern in VB.Net 9.0

JaredPar
+1  A: 

See my answers here:

To summarize:
VB.Net does not have yield, but C# implements yield by converting your code to a state machine behind that scenes. VB.Net's Static keyword also allows you to store state within a function, so in theory you should be able to implement a class that allows you to write similar code when used as a Static member of a method.

Joel Coehoorn
A: 

Behind the scenes, the compiler creates an enumerator class to do the work. Since VB.NET does not implement this pattern, you have to create your own implementation of IEnumerator(Of T)

Thomas Levesque