What are the fundamental differences between Java and C# in terms of inner/local/anonymous classes?
views:
152answers:
2What are the fundamental differences between Java and C# in terms of inner/local/anonymous classes?
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.
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.