C# and Java

Published (last updated )

Object creation

In Java, all objects are created on the heap (using the “new” keyword). In C# this works the same way but additionally also supports stack-based classes (called “value types”).

Exception handling

Both languages support things like “try” “catch” and “finally”. Both languages support methods for getting a stack trace but only Java exceptions have methods that allow one to alter the stack trace. In C#, all exceptions are unchecked and there is no analog to the “throws” clause. One major side effect of this is that unless the creator of the API explicitly documents the exceptions thrown then it is not possible for the users of the API to know what exceptions to catch in their code.

Main

The main method in Java begins with a lowercase “m” (as do all Java method names by convention). The main method in C# begins with an uppercase “M” (as do all C# method names by convention). Additionally the Main() method in C# can have a void parameter.

Namespacing

In Java, the package names dictate the directory structure of source files in an application whereas in C# namespaces do not dictate the physical layout of source files in directories only their logical structure.

Constructors and Destructors (and Finalizers)

Both C# and Java have constructors. C# also has the concept of destructors ala C++ with Java finalizer semantics. Although finalizers exist in Java, doing work within them gives problems as there is no way to control the order of finalization (example: if objects that hold references to each other are finalized out of order). Finalizers aren’t removed after the garbage collection thread runs but instead are eliminated after the finalization thread runs (possible overhead issues).

Access modifiers

Five in C#, three in Java. Default for Java is protected; in C# it’s private. C# has extra modifiers because of assemblies (which are collections of packages ala Jars).

Reflection

Reflection in C# is done at the assembly level while reflection in Java is done at the class level. Since assemblies are typically stored in DLLs, one needs the DLL containing the targeted class to be available in C# while in Java one needs to be able to load the class file for the targeted class. Additionally C# has a ParameterInfo class which contains metadata about the parameters of a Method while Java uses Class objects for that which lose some information such as the name of the parameter.

Declaring constants

Works almost identically. Additionally, Java also supports having “final” parameters to a method. This functionality is non-existent in C#. The primary use of “final” parameters is to allow arguments to a method to be accessible from within inner classes declared in the method body.

Nested classes

C# has the equivalent of Java’s static nested classes but has nothing analogous to Java’s inner classes. In Java a nested class can be declared in any block of code including methods, this is not the case in C#.

Threads

In Java a method that shall run in a multithreaded context is designed up front specifically with that in mind (by subclassing the java.lang.Thread class and overriding its run() method or by implementing the java.lang.Runnable interface and implementing the run() method). On the other hand, in C# any method can be passed to a ThreadStart object and run in a multithreaded scenario (by creating a new System.Threading.Thread object and passing it a System.Threading.ThreadStart delegate).

Volatile

Currently the Java Memory Model does not prevent reordering of writes to volatile variables with writes to other variables so it is possible that the new object is constructed before the helper reference is made to point at the newly created object meaning that two objects are created. Also it is possible that the helper reference is made to point at a block of memory while the object is still being created meaning that a reference to an incomplete object will be returned. In C#, the semantics of volatile prevent such problems from occurring because reads and writes cannot be moved backward or forward across a volatile write. Also in C#, being marked as volatile also prevents the Just In Time compiler from placing the variable in a register and also ensures that the variable is stored in global memory on multiprocessor systems.

Rubin’s note: As of J2SE 5.0, this problem has been fixed. The volatile keyword now ensures that multiple threads handle the singleton instance correctly. for Java 1.4 a workaround was to synchronize getHelper but that can lead to serious performance issues.

Operator Overloading

Java has no operator overloading, C# does. There is ongoing debate about wheter this is a plus.

Switch statements

In C#, switch statements support the use of string literals and do not allow fall-through unless the label contains no statements.

Goto

Unlike Java, C# contains the goto statement which can be used to jump directly from a point in the code to a label.

Virtual methods

In Java all methods are virtual methods while in C#, as in C++, one must explicitly state which methods one wants to be virtual since by default they are not.

Multiple Classes in a Single File

In Java, there can only be one class per source file that has public access and it must have the same name as the source file minus the file extension. C# does not have any restrictions on this.

Events

There is no general mechanism for event handling in Java. Instead there are design patterns that are used by the GUI classes which developers can take their cue from. An event is typically a subclass of the java.util.EventObject class. C# uses delegates to provide an explicit mechanism for creating events. An event is typically a subclass of the System.EventArgs class.

Delegates

Delegates are a mechanism for providing callback functions. Delegates are akin to function pointers in C or functors in C++. To get the same functionality as C# delegates in Java, one can create interfaces that specify the signature of the callback method such as is done with the Comparable interface although this has the drawback of forcing the method to be an instance method when it most likely should be static.

Enumerations

Java’s lack of enumerated types leads to the use of integers in situations that do not guarantee type safety. Thus in Java, developers are left to check type safety in their code whereas in C# it can be done automatically by the compiler. A workaround for the lack of enumerations in Java is to use a class as your type and various static instances of the type as your variable.

Value Types

In both Java and C#, items on the heap have to be garbage collected to reclaim the memory allocated to them when they are no longer in use while stack based objects are automatically reclaimed by the system. In Java, all classes are created on the heap while primitives are created on the stack (see Object Creation). This can lead to situations where objects that are used similarly to primitives in a program tend to hang around and wait for garbage collection. C# has a mechanism that allows one to specify that objects of a certain class should be stack based. Unlike classes, value types are always passed by value and are not garbage collected. To do this you use the struct keyword instead of class. In situations where value types need to be treated as objects, the .NET runtime automatically converts value types to objects by wrapping them within a heap-allocated reference type in a process called boxing.

Properties

In C#, properties are a way to abstract away from directly accessing the members of a class, similar to how accessors (getters) and modifiers (setters) are used in the Java world. The use of properties as an abstraction may fall apart if the property throws an exception. When this occurs users of the object must then treat operations that look like member accesses as if they were method calls which can lead to unintuitive looking code (workaround: take care of the exceptions outside of the property).

Multidimensional Arrays

C# makes the distinction between multidimensional and jagged arrays. A multidimensional array is like the same in C or C++. A jagged array is akin to an array in Java which is an array of arrays. The lack of true multidimensional arrays in Java has made it problematic to use Java in certain aspects of technical computing which has lead to various efforts to improve this position including research efforts by IBM which involved writing their own Array class to get around the shortcomings in Java arrays.

Preprocessor Directives

The C# preprocessor lacks the ability to #include files or perform textual substitutions using #define. You can #define and #undef identifiers and also the ability to select which sections of code to compile based on the validity of certain expressions via #if, #elif, and #else. The #error and #warning directives can be used for custom messages. The #line directive can be used to specify the source file and line number reported when the compiler detects errors. Java does not do anything like preprocessor directives.

Pointers and Unsafe

It is possible to have pointer types in C# if code is executing in an unsafe context. This disables almost all safety nets which are the benefit of a managed environment.

Pass By Reference

In Java the arguments to a method are passed by value meaning that a method operates on copies of the items passed to it instead of on the actual items (Java does manipulate objects by reference, and all object variables are references). In C#, it is possible to specify that the arguments to a method actually be references to the items being passed to the method instead of copies. This can be helpful if you want to create methods that return more than one object.

Explicit Interface Implementation

A FileRepresentation class which has a graphical user interface may implement an IWindow and an IFileHandler interface. Both of these classes may have a Close method where in the case of IWindow it means to close the GUI window while in the case of IFileHandler it means to close the file. In Java, there is no solution to this problem besides writing one Close method that does the same thing when invoked via an IWindow handle or an IFileHandler handle.