In C# you can use a for-loop without declaring the body, what is the benefit of using this in production-code versus using a foreach loop?
Example
My Examples below use reflection to get the property value of an object based on the p_strPropertyPath parameter. The method can also look at the property of a property, for example MyClass.Property.SubProperty.
In my opinion, the foreach loop is more obvious at what it is supposed to do, whereas the former looks cleaner to me.
Body-less For Loop
The example below uses a body-less for-loop and an enumerator:
private string GetValue(MyClass p_objProperty, string p_strPropertyPath) { string[] lstProperties = p_strPropertyPath.Split('.'); IEnumerator objEnumerator = lstProperties.GetEnumerator(); object objValue; for ( objValue = p_objProperty; objValue != null && objEnumerator.MoveNext(); objValue = objValue.GetType().GetProperty(objEnumerator.Current as string).GetValue(objValue) ) ; return Convert.ToString(objValue); } foreach loop
The example below uses a foreach loop:
private string GetValue(MyClass p_objProperty, string p_strPropertyPath) { string[] lstProperties = p_strPropertyPath.Split('.'); object objValue = p_objProperty; foreach (string strProperty in lstProperties) { objValue = objValue.GetType().GetProperty(strProperty).GetValue(objValue); if(objValue == null) break; } return Convert.ToString(objValue); }
objValue.forloop (a bit too clever).foreachloops are meant to replaceforloops in those instances where you don't require the loop variable as an index. Theforeachis especially useful here, where it replaces something that's rather unreadable with something that is quite readable.p_xxxvariables? Please don't use Hungarian notation in C# code. Use meaningful variables names that clearly convey what the variable does. Even though he deleted the comment, I'm with @RobertHarvey and would want to have stern words with anyone on my team who wrote code like the first example. Always write code so that it is easy to read and thus obvious what it does.