What are the fundamental differences between Java and C# in terms of inner/local/anonymous classes?
-
Duplicate of http://stackoverflow.com/questions/521305/why-should-i-learn-c http://stackoverflow.com/questions/325046/java-or-net and many others – Welbog Mar 26 '09 at 14:51
-
It's not a dupe - look at the title. It's asking about specific differences. I'll edit the question to make this clearer. – Jon Skeet Mar 26 '09 at 14:54
-
I hardly think this qualifies as an "exact duplicate". – Tom Hawtin - tackline Mar 26 '09 at 14:54
-
Re the dup, I'm not so sure - for me, this is quite a specific question. I'd vote for re-open if it closes... – Marc Gravell Mar 26 '09 at 14:55
-
It's a subset of those questions, whose answers are filled with resources that cover the differences between the languages. It's not an exact duplicate, but it is evidence that Sasha made no effort to search SO on his own before asking the question. – Welbog Mar 26 '09 at 14:56
-
I'll vote for a reopen if this is closed. For now, I'll remove the discussion on duplicates from the question, since it really belongs in the comments. – Michael Myers Mar 26 '09 at 14:56
-
If Sasha wants to roll back fundamental changes made by jonskeet, et. al., then it's a duplicate. If he wants to retain those changes, then maybe not. Your call, Sasha. – George Stocker Mar 26 '09 at 14:57
-
@welbog: Neither of those answers includes the word "anonymous" or "inner". This is clearly a very specific question - I see no reason to mark it as a duplicate at all. – Jon Skeet Mar 26 '09 at 15:07
2 Answers
C# doesn't have the equivalent of Java inner classes - it only has nested types (like Java's "static" nested classes).
The access rules are slightly different - in Java, an outer class has access to its nested class's private members, and vice versa. In C# the nested class has access to the outer class's private members, but not the other way round.
C# doesn't have anonymous inner classes like Java, but it does have anonymous methods and lambda expressions, which are a much cleaner way of achieving most of what anonymous inner classes are usually used for. The variable capture for the two mechanisms is different - see my article on closures for more details.

- 1,421,763
- 867
- 9,128
- 9,194
In my mind, the biggest difference is how they (anonymous classes in java vs anonymous methods in C#) handle captures. In java, it captures the current value of the variable (the original and captured value are then isolated). In C#, you capture the variable itself. This is double edged, and can lead to problems - but is incredibly powerful when used correctly.

- 1,026,079
- 266
- 2,566
- 2,900