When talking to a friend of mine we had the idea to do a blog series over C# functions that might help people if they don?t know about them. This will be categorized so you can keep up on it, and it will be once a week on Mondays. First I was going to start with ?continue?. Nest ifs inside a loop cause major performance issues in most applications but there are a few ways to avoid this. The MSDN definition of continue is ?The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.? . Here is the code snippet that we are going to clean up. ?Caution the following code is not suitable for young viewers or those that are faint of heart.?
IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();
foreach (var parameter in test)
{
if (parameter != null)
{
parameter.MethodName = "Something";
if (parameter.children != null)
{
foreach (var child in parameter.children)
{
if (child.MethodName == null)
{
child.MethodName = "Something";
}
}
}
}
}
I know right? We can clean this up by inverting the first if to a continue statement.
IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();
foreach (var parameter in test)
{
if (parameter == null) continue;
parameter.MethodName = "Something";
if (parameter.children != null)
{
foreach (var child in parameter.children)
{
if (child.MethodName == null)
{
child.MethodName = "Something";
}
}
}
}
We can still clean this up by inverting the children check to a continue statement.
IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();
foreach (var parameter in test)
{
if (parameter == null) continue;
parameter.MethodName = "Something";
if (parameter.children == null) continue;
foreach (var child in parameter.children)
{
if (child.MethodName == null)
{
child.MethodName = "Something";
}
}
}
We can also do this to the if inside the second for each loop.
IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();
foreach (var parameter in test)
{
if (parameter == null) continue;
parameter.MethodName = "Something";
if (parameter.children == null) continue;
foreach (var child in parameter.children)
{
if (child.MethodName != null) continue;
child.MethodName = "Something";
}
}
This is a much cleaner section of code but is not great. It still has a nested for each loop. which makes my insides scream, but we will attack that sort of nesting next week.
74ae59a2-f4a0-4824-a715-9cb1fcc17c96|1|5.0
.NET, Productivity, C# Helpful Functions