C#
vs Java
C#,
the new programming language from Microsoft, promises
to deliver everything Java does and more. A look at
how they compare. by Ajay Barve
C#
(pronounced C-Sharp) a hybrid of C and C++ is Microsoft's
answer to Sun's popular Java programming language
and a part of Microsoft's grand .NET initiative. C#
is touted as "the first component-oriented language
in the C/C++ family."
C# boasts type-safety, garbage collection, simplified
type declarations, versioning among other features
that make developing solutions faster and easier,
especially for COM+ and Web services.
However, despite the claim, many people think that
C# is rather a clone of, or Microsoft's replacement
for, Java. Let's compare the two languages and check
if C# is more than inspired by Java.
A broader view
The best way to compare C# with Java would be
to take a Java application and translate it into C#
.We are going to do just that and find the difference
between the two implementations. We will focus specifically
on the syntax of C#. On a high level we will point
out when the syntactical structures are the same,
and spend time talking about when they are different.
There are a few syntactical "extras" in
C# that do not have equivalents in Java.
Understanding Datatypes
Java has quite a few primitive data types: byte,
char, int, long, floats, double. Primitives are the
basic building blocks of Java; they are the smallest
"unit." What usually annoys most programmers
is that whereas all objects in Java extend from java.lang.Object,
primitives do not extend from anything. This means
that any class that operates on objects will not work
with primitives. The primitives must be mapped into
the object model in order to use it.
This is not the case in C#. C# uses the .NET object/type
system so that C# programs may inter-communicate with
other .NET languages without having type confusion
for example, the type int is an alias to System.Int32
which in turn ultimately extends from System.Object.
This means that the primitive, or simple, types in
C# function just like any other object.
Statement comparisons
Simple statements in C# and Java look alike,
since both languages descend primarily from C and
C++. The difference between keywords 'import' in Java
and 'using' in C# is that Java has a concept of packages,
while C# uses namespaces much like those of C++. The
'using' keyword makes all names in the given namespace
accessible to a module. So, the line using System
lets you access the .NET runtime namespace System.
The System namespace contains the static global method
System.Console.WriteLine(), which is accessible as
Console.WriteLine() without specifying the System
namespace. In the Java example, System is a class
defined in java.lang, which is implicitly imported
into every Java source file; therefore, the import
statement is not needed.
Declarations in C#
Variables are defined in C# just like they are in
Java.
int integer = 3;
bool boolean = true;
Java uses the "static final" keywords to
make a variable constant; in Java a "static final"
variable is class-scoped instead of being object-scoped,
and the compiler prevents any other object from changing
the value of the variable. C#, in turn, has two ways
of declaring a variable constant. Marking a variable
const causes the value to be in lined before compiling.
With the definition
const
int TWO = 2; the expression
2 * TWO is converted to 2 * 2 by the preprocessor
before compilation. This causes the compiled program
to run faster as it does not have to look up the value
of the constant during run-time.
Considering that constants are often used for things
like BUFFERSIZE or TIMEOUT, it may be desirable not
to have this into the code; if this field is marked
const, then any code compiled against it will inline
the constant and will need to be recompiled for it
to change. If the constant is instead marked with
read only, then the next time the application is executed
the behavior will change as the code will check the
value of the read only field, while the compiler still
protects it from being programmatically changed.
Conditional Statements
C# has both the structures that Java programmers
expect, the "if-then-else" and "switch"
statements. Both behave similarly except for one difference
in the C# "switch" statement syntax.
Java allows for control flow to implicitly fall between
different cases in the switch statement, whereas the
C# compiler explicitly does not allow this, the C#
compiler will mark this as a syntactical error. For
example, in Java the following is valid:
int switchcase = 3;
switch(switchcase) {
case 3:
System.out.println( "World" );
default:
System.out.println( "Peace" );
}
This will result in both printlns being executed.
In C#, an explicit break or goto case is required
somewhere in the case to explicitly define the control
flow.
Writing Loops
Like Java, C# has the "while", "do-while"
and "for" loops. On top of these three,
C# has introduced a "foreach" loop that
operates on objects that implement the System.Collections.IEnumerable
interface. Most notably, arrays in C# (System.Array)
implements IEnumerable, so the following Java code
int[] array = // something...
for( int count=0;count<array.length;count++ )
System.out.println( array[count] );
is legal in C#, but it can also be represented in
C# as foreach( int member in array )
Console.WriteLine( member );
Specifically, the IEnumerable interface provides the
ability to get an IEnumerator representation to an
object (similar to java.util.Enumeration). Anything
which implements the IEnumerable and IEnumerator interfaces
can be operated on by the "foreach" loop.
Break and Control Transfer Statements
Most of the Java jump statements (continue, goto,
and return) map into C#. These statements are used
the same way they are used in Java: to break out of
loops or to return control to a different block.
What deserves a discussion is the exception model,
as it differs both semantically and syntactically.
All exceptions in C# are run-time exceptions; the
compiler is not going to help the programmer keep
track of exceptional situations. It should also be
noted that method signatures do not contain the exception
that can be thrown inside the block. My warning to
Java programmers turned C# programmers: be very careful.
The "try-catch-finally" block that Java
programmers are familiar with exists in C# and so
do a few additional syntactic sugars. All exceptions
derive from System.Exception, so catching System.Exception
will catch all possible exceptions thrown in a block,
just like in Java. A shortcut is available if the
exception object is not needed by using the following
framework:
try {
// something that may throw an exception
} catch {
// deal with the exception without getting a handle
// to the exception object
}
But if you do need to catch a specific exception (while
again not requiring the exception object), try something
like
try {
} catch( IOException ) {
}
Constructing an Object
The concept of Object, Class and inheritence
in C# is similar to Java.The diffrence is in the syntax.
All classes in C# descend from the System.Object class,
just as all classes in Java descend from the java.lang.Object
class. Defining a class which extends to another class
would be written using ':' instead of the extends
keyword. For example if a class B extends class A
it would be written as follows,
class A : B{ }
The confusion is apparent when you implement an interface
that again uses the ':' instead of the implemented
keyword. If a class implements multiple interface
they will be added to the comma separated list. So
a class D which extends class B and implements interface
C will be as follows,
class D : B, C {
}
Java programmers may get annoyed with C# as it muddles
the two together: interfaces may also be placed after
the colon, and the compiler will only demand that
the class it extends (if the class directly extends
another) is the first listed after the colon.
The default access modifier for classes in C# is to
make them "internal," meaning they are not
accessible from any other object outside the .cs file
in which they are defined. The more familiar "public,"
"private," and "protected" modifiers
are provided along with a fifth "protected internal"
modifier which is the union of "protected"
and "internal" properties (the modified
can be accessed from a class which extends the enclosing
class, or from within the file in which it has been
defined). In the Hello example above, both the Java
and the C# class are defined to be "public,"
although they do not need to be. Neither class provides
functionality that any other object may wish to use
they simply provide the proper signature so that the
run-time environment may execute them.
Page
1 2