by Vahid
25. January 2009 15:30
here is a quick comparision between microsoft c# (.net) and java
| Concept |
C# |
Java |
Notes |
| Virtual machine |
CLR |
JVM |
CLR is not quite the same as JVM concept, but very similar. |
| Namespace |
namespace/
using |
package/
imports |
C# allows multiple namespaces in a file, Java does not. |
| Attributes |
[attribute] |
@annotation |
C# 1.0, Java 1.5 |
| Base class |
base |
super |
|
| abstract objects |
abstract class |
abstract class |
|
| abstract methods |
abstract |
abstract |
|
| sealed objects |
sealed |
final |
In both cases, sealing is discouraged. |
| sealed methods |
sealed |
final |
|
| replacement methods |
new keyword |
not supported |
Effectively ignores the base method. |
| constants |
const / readonly |
final static |
|
| Enum's |
enum keyword |
enum keyword |
C# 1.0, Java 1.5 |
| virtual functions |
explicit virtual |
always virtual |
This is one of the gotcha's when working between the two languages |
| override intention |
override |
@Override (though members override by default) |
Causes compiler error if method is not actually overriding a base method. |
| Class/Type representation of simple types |
Map 1:1 with the simple type keywords. |
Behave different to simple type keywords. |
C# seems more natural than Java in it's behavior |
| Getters/Setters |
get/set keywords, behave like properties |
Explicit get/set methods |
Again, C# seems more natural with this. |
| Events |
Typically via delegates |
Typically via interfaces |
|
| Reference equivalence |
Object.
ReferenceEquals()
|
== |
Another C# vs Java gotcha. |
| Value equivalence |
== or
Object.Equals()
|
object.equals(),
== for value types
|
Java's choice of using == for reference equals adds to the need to distinguish between objects and value types. |
| Object introspection |
Object.GetType() |
object.class |
Very similar |
| Exceptions thrown by method |
implicit |
throws keyword |
Actually liking Java's philosophy here, albeit taking some getting used to. |
| Stack scoping |
using keyword, or try/finally keywords |
try/finally keywords |
'using' keyword is syntax sugar that calls IDisposable.Dispose() method at end of block. |
| Simple synchronization |
lock keyword |
synchronized keyword |
'synchronized' can also be used on a method. |
| Generics |
class<type> |
class<type> |
C# 2.0. Java 1.5. C# has a cleaner implementation and discovery of generics in reflection. In Java, class and class<type> cannot co-exist. class becomes synonymous to class<object>. |
| Output parameters |
out, ref |
Not allowed |
Not a huge loss in Java, there are simple workarounds. |
| Switch fall-through |
Not allowed |
Allowed |
|
| iteration |
foreach(type x in y) |
for (type x : y) |
C# 1.0. Java 1.5. |
| Lambda/Closures |
=> |
(future) |
C# 3.0. Java 1.7 (maybe) |