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 Article source: http://ezine.softbath.net/computer/C-vs-Java-348.php
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
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.
Methods
At the basic level there are no differences between C# and Java methods; each method takes parameters, and has a return type.
class A {
public void MethodA1() { }
public int MethodA2() { }
public void MethodA3( int i ) { }
public int MethodA4{ int i ) { }
}
This creates a class A that has one method named MethodA1 that does not take any parameters and does not return any value. MethodA2 returns an integer, MethodA3 takes an integer as a parameter.
However, C# can do things with methods that could not be done before with Java.
Method signature and params
When calling a method, the Java compiler checks that there is a method that matches its signature. For example, in Java, if there is a method defined as
public void methodCaller( int a, int b, int c );
then a call of that method
methodCaller( 3, 4, 5, 6 );
will generate a compiler error as the Java compiler cannot find a method named methodCaller that takes four ints. We cannot create a method signature that allows us to take a variable number of ints as parameters.
Why should this even matter? If a programmer wants to take a variable number of ints, he can define a method signature that takes an array of integers and then construct the array when calling the method. In Java, this will take at least three lines of code just to call the method the first to create the array, one or more lines to assign values into the array, and the third to call the method.
C# eases this issue by allowing programmers to place a params modifer on the last array parameter of the method, so that a variable number of parameters can be passed into it. Using the above example, the method signature can be defined as
public void methodCaller( params int[] a );
and the method can be called with any of
methodCaller( 1 );
methodCaller( 1, 2, 3, 4, 5 );
Inside methodCaller, the parameters can be accessed through the "a" array defined.
Passing by reference and out
C# can also force a parameter to be passed in by reference as opposed to being passed by value. Let's consider a primitive type,
public void increment( int a ) {
a++;
}
int a = 3;
increment( a );
// a still == 3
will not cause the variable passed into increment to actually be incremented because "a" is being passed in by value; the variable a in the increment block is in a different environment, and therefore changes in that scope do not propagate back out.
However, changing the method to
public void increment( ref int a ) {
a++;
}
int a = 3;
increment( ref a );
// a now == 4
will cause the int "a" to be passed in by reference (just as classes are passed in) and therefore modifying it will cause the original value to be changed. Using ref with a class allows a function to reassign the class pointer inside the function and have that change propagate outside the method.
A natural partner to ref is the out keyword. While ref does not guarantee that any operations will actually be performed on the variable, using out will cause the compiler to make sure that a value has been set to the variable. Code such as
public void DoNothing( out int a ) { }
will cause the compiler to complain as "a" is not assigned to anything.
Properties
Properties is a C# construct that formalizes the get/set pattern seen in many Java classes. The Java paradigm of having a get method that takes one parameter and a set method that returns the said parameter is compacted. So the following Java code:
private int name;
public int getName()
{
return this.name;
}
public void setName( int name )
{
this.name = name;
}
can be written in C# as
private int property;
public int Property {
get {
return this.property;
}
set {
// value is an implicit variable generated by the
// compiler to represent the parameter
this.property = value;
}
}
Behind the scenes, C# actually compiles the property to two methods in the .NET intermediate language framework named get_Property and set_Property. These methods cannot be called directly from C#, but other languages using the MSIL should be able to access these getters/setters.
Accessibility Modifiers
Access modifiers restrict the ability for only certain code to change a field. The ones that a Java programmer is used to are private, protected, default, and public.
C#, in turn, has five modifiers:
* Public: means the same thing that it means in Java. As long as you can get to the enclosing object, any thing has free access to this member.
* Protected: yet again, the same thing as Java. Free reign over the member from classes that extend the containing classes.
* Internal: this is a new one to Java programmers, as this means that a member is accessible from the entire assembly. All the objects you define inside a .cs file (you can define more than one object inside the .cs file, unlike Java, where you can usually define only one object) have a handle to the internal member.
* Protected internal: think of this one as the union of protected and internal, as the item it is modifying is either protected or internal. This item can be accessed from the entire assembly, or within objects which derive from this class.
* Private: just as in Java. Nothing except the enclosing class may access this.
These modifiers can be applied to the same structures and modify the accessibility to objects, methods, and variables.
Source Files
In Java, each class needs to exist in a like-named file (with the like-named extension .java) there are exceptions with class visible and inner classes, as those are defined within another class's .java file.
C# does not have this or any restriction when it comes to defining classes, even when they are in different namespaces any part of a C# program may exist in the same .cs file, so as to form a self-contained unit.
File Naming Convention
C# follows mixed-caps style, except that method names typically also capitalize their first letter. It is also common to see that variables in the BCL (Base Class Library) have capital letters as the first character, although most user-defined variables are defined with a lowercase first letter.
There is no distinction made between the naming convention of constants and assignable variables, as both use mixed caps.
