An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
I'm using break(); on this example.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
My method is async Task like following.
public async Task MyMethod()
{
string[] lists = GetCustomerLists();
foreach (string lst in lists)
{
// do somethong
// if meet some condition to return
????
}
}
What is the correct way to return from the method among the followings?
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
Answer accepted by question author
I'm using break(); on this example.
just return or break if you want fall though to the end of the method.
because it is an async method, the compiler will convert the return/exit to a return task.
Here is an abstract example where all Customers from a specific country are returned in a class named CustomerOperations.
This it's Entity Framework but that doesn't matter, the same applies for other read operations. Think of context.Customers as string[] lists = GetCustomerLists();
public static async Task<List<Customers>> ByCountry(int countryIdentifier)
{
return await Task.Run(async () =>
{
await using var context = new NorthwindContext();
return await context.Customers
.Where(customer => customer.CountryIdentifier == countryIdentifier)
.Select(customer => customer)
.ToListAsync();
});
}
Usage
public static async Task Demo()
{
int identifier = 12;
var customers = await CustomerOperations.ByCountry(identifier);
}