I’m trying to convert a proprietary string mask to the .net equivalent of it. For that I need to exchange every occurance of [someText] with {aDigit}.
private static int hits = 0; private static object hitsLock = new object(); public static string ConvertSdsFileMaskToStringMask(string sdsFileMaskString) { Regex bracketsExpression = new Regex(@'\[[^[]*]'); lock (hitsLock) { hits = 0; return bracketsExpression.Replace(sdsFileMaskString, ReplaceSquareWithAngularBrackets); } } private static string ReplaceSquareWithAngularBrackets(Match m) { string result = String.Format('{{{0}}}', hits.ToString()); hits++; return result; }
It works. But both expressions need to know each other’s workings and are depending on the hits counter. I feel this could be improved. Ideally both have no dependency on each other. Any suggestions? This can probably be done better. Any suggestions?
Yes – use an anonymous method or lambda expression:
This will capture the local variable in a new (compiler-generated) type, getting rid of the ‘globalness’.
If you’re happy with side-effects, you could make the lambda expression simpler, too. I’d also get rid of the call to String.Format in this case, as all those braces are confusing: