Tom Gullen Tom Gullen - 1 year ago 79
C# Question

Break out of parent function?

public static void CacheUncachedMessageIDs(List<int> messageIDs)
var uncachedRecordIDs = LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs);
if (!uncachedRecordIDs.Any()) return;

using (var db = new DBContext())

The above method is repeated regularly throughout the project (except with different generics passed in). I'm looking to avoid repeated usages of the
if (!uncachedRecordIDs.Any()) return;

In short, is it possible to make the
return the

This will guarantee a new data context is not created unless it needs to be (stops accidentally forgetting to add the return line in the parent method).

Answer Source

It is not possible for a nested method to return from parent method. You can do some unhandled Exception inside GetUncachedRecordIDs, that will do the trick, but it is not supposed to do this, so it creates confusion. Moreover, it is very slow.

Another not suggested mechanic is to use some goto magic. This also generates confusion because goto allows unexpected behaviour in program execution flow.

Your best bet would be to return a Result object with simple bool ShouldReturn field and then check it. If it passes, then return. This solution solves the problem of calling a method, which is Any() in this case.

var uncachedRecordIDsResult = LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs);
if(uncachedRecordIDsResult.ShouldReturn) return;

My reasoning for lack of this feature in the language is that calling GetUncachedRecordIDs in basically any function would unexpectedly end that parent function, without warning. Also, it would intertwine closely both functions, and best programming practices involve loose coupling of classes and methods.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download