2
  string json = "{ "Name": "Tom" }";
  var regex = new Regex(@"\\x([a-fA-F0-9]{2})");
  json = regex.Replace(json, match => char.ConvertFromUtf32(Int32.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber)));

The variable "match" is not defined in my code. The code executes without problem but I'd like to know why C# does not complain that it is undefined? Right after this code, if I write:

x = 1;

C# will complain that x is not defined. What's going on?

Johann
  • 27,536
  • 39
  • 165
  • 279
  • 3
    The `match =>` is the declaration. – mattmanser Dec 04 '13 at 10:39
  • 1
    http://msdn.microsoft.com/en-us/library/bb397687.aspx – zerkms Dec 04 '13 at 10:40
  • 1
    Did you ever heard of Lambda expressions? – DHN Dec 04 '13 at 10:40
  • Compiling is the 2nd part, first how is it not giving error on `match.Groups[1].Value` code if it is not defined? – Shaharyar Dec 04 '13 at 10:40
  • btw; you would be well-advised to use a JSON parser here; JSON is not a "regular" language, so will have most of the pitfalls that impact html: http://stackoverflow.com/a/1732454/23354 – Marc Gravell Dec 04 '13 at 10:48
  • @MarcGravell Normally that is true, but not in this case. The real json data I deal with contains javascript hex literals: \x2c, etc. The json parser cannot handle that. But that's a different issue. – Johann Dec 04 '13 at 10:52

2 Answers2

5

Here, match is declaring the parameter - therefore match is perfectly well-defined inside the lambda. Essentially (since this is compiling to a delegate), this is all syntactic sugar for something very similar to:

static string HazNoName(Match match)
{
    return char.ConvertFromUtf32(Int32.Parse(match.Groups[1].Value,
         System.Globalization.NumberStyles.HexNumber));
}
//...
json = regex.Replace(json, new MatchEvaluator(HazNoName));

(although actually the C# compiler will cache and re-use the delegate instance in this case, since there is no captured context)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Ok. Never heard of Lambda expressions. The => is what threw me off. I should have recognized that this was not the same thing as >=. – Johann Dec 04 '13 at 10:50
0

match is a parameter in the lambda expression, why should the compiler complain?

Lambda Expressions

DGibbs
  • 14,316
  • 7
  • 44
  • 83