|
|||||||||||||||||||||
|
|||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
Contents
IntroductionC# like Java is a "simple, object oriented, distributed, interpreted, robust, secure, portable, high performance, multithreaded and dynamic language". C# goes a step further and implements features like "cross-language interoperability" and "mixed language programming". It supports component-based programming and is well suited for distributed web applications. Not being closely coupled with Windows OS could be considered as another drawback of Java since Windows is the most widely used operating system. Even though both Java and C# have inherited features from C and C++, C# cannot be considered as a successor of Java. Rather, they could be considered as peers, having a lot in common but unique in their own ways. C# was developed keeping the .NET platform in consideration, and hence is the most likely choice for developing .NET applications. In short, C# is a simple but a powerful language which is conceptually like C, powerful like C++, elegant like Java, and useful like VB. Object Oriented ParadigmBoth Java and .NET treat data as a critical element in program development. Every problem is decomposed into a number of entities called 'objects' and then build data and functions around these entities. A software object consists of a set of related data and functions. Both follow a single rooted object hierarchy. Every class in the Java framework is a subclass of Runtime EnvironmentCLR (Common Language Runtime) manages the execution of programs in the .NET environment. When a C# code is compiled, the output is not an executable but an intermediate code, called the MSIL (Microsoft Intermediate Language). MSIL is a set of assembly level instructions that are platform independent and conceptually equivalent to the byte codes in Java. The CLR then translates the MSIL into executable code when run using the JIT (Just In Time) compiler. CLS (Common Language Specification) is a set of rules the .NET compiler should adhere to so as to facilitate interoperability with other languages. CTS (Common Type System) is a subset of the CLS and it must be implemented by every .NET compiler. CLS and CTS are both implemented by C#. Most importantly, the specification has been opened up (using open standard technologies like XML and SOAP), so that it can be ported to non-Windows platforms. The CLR is well designed as compared to the JVM (Java Virtual Machine) and supports execution of both managed and unmanaged code. .NET can be considered as an extension of CLR with extra features like Windows Forms and Enterprise Services. The basic difference between the JVM and C# is that the C# compiler produces an executable code. Compiling and Running programs from Command LineIn Java: > javac <program_name>.java
> java <program_name>
In C#: > csc <program_name>.cs
> <program_name>
C# has a highly sophisticated IDE, Visual Studio .NET, better than any of the Java IDEs. Namespaces and ClassesNamespaces are used to semantically group elements for organization and readability of classes and other namespaces. Names declared in one namespace will not conflict with the names declared in another namespace. It can be nested to any level. They are analogous to packages in Java. package mySpace1.mySpace2.mySpace3;
class FirstClass
{
}
A specification in Java (shown above) would be equivalent to the code shown below in C#: namespace mySpace1
{ namespace mySpace2
{
namespace mySpace3
{
class FirstClass
{
}
}
}
}
AliasesThe using printpath = System.Console;
class testApp{
static void Main ( ) { printPath (“Alias test”); }
}
Pre-processor DirectivesUnlike in Java and like in C/C++, C# supports the use of pre-processor directives like Constructors, Destructors and Garbage CollectionIn both Java and C#, classes are instantiated using the <access modifier> <classname>
{
/* constructor code */
}
Recovery of memory from unused objects is a key aspect of dynamic allocation scheme. In C#, this is accomplished in the following two ways:
~<classname>
{
/* constructor code */
}
Multiple Main methodsUnlike Java, C# supports use of multiple MultipleMain.cs /main:<class name>
Comparison of KeywordsUnlike Java, all data types in C# are objects. The keyword set in C# is richer since it has lot more keywords than Java. C# contains the following keywords in addition to almost every keyword contained in Java: ConstantsJava uses the ReadOnly fieldThis is similar to the directive Verbatim StringsThe Verbatim string literals are defined by enclosing the required string in the characters string pathname = @"C:\Programs\"
Value TypesFor efficiency purposes, CTS (Common Type System) is divided into 2 categories:
Access ModifiersThe scope of the Type SafetyC# is a robust language and provides number of type safety measures. It does not permit unsafe casts, checks for array bounds, reference parameters passed are type safe, and all dynamically allocated objects are initialized to zero. IndexersAn indexer allows an object to be indexed like an array. Both Java and C# support indexers. The main use of indexers is to support the creation of specialized arrays that are subject to constraints. element_type this [int index]
get{
/* return the value specified by index */
}
set{
/* set the value specified by the index */
}
Global MethodsLike in Java, methods have to be a part of a class and no global methods are allowed. Both support automatic destruction of objects when they are out of scope (or do not have any references) and memory management. foreach statementThe Switch statementThe Goto statementJava does not support ‘goto’ statement. Even though much maligned, C# supports the Virtual methodsIn Java, all methods are virtual methods by default. C# follows the C++ model in which the methods must be explicitly specified as virtual using the Jagged ArraysJagged array is a unique feature of C#. It is an array of arrays in which each array is of variable size. It can be considered as a table in which the lengths of all the rows are not the same. Java has no provision for such an array. CollectionsBoth in Java and C#, a collection is an object that groups multiple elements into a single unit. Collections are used for storing, retrieving, manipulating and transmitting data from one method to another. The EnumeratorAn public enum Days {
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
BoxingIn Java, the primitive data types have to be placed in the appropriate wrapper classes before being used as 'objects'. In C#, this is done by 'boxing' in which the wrapper class is implemented implicitly without exposing the programmer to it. C# allows conversion of any value type to a corresponding reference type, and to convert the resultant 'boxed' type back again. This is used when value types are to be accessed as objects. int val = 101;
object box = val;
if (box is int)
{
Console.Write ("Box contains an int");
}
ReflectionReflection enables one to find out the type of an object. The C# also has 3 keywords for runtime type identification.
InheritanceBoth C# and Java support single level inheritance only, and multi-level inheritance is accomplished by implementing interfaces. Both Java and C# can block inheritance of a class using the keyword Superclass Constructor
Exception HandlingBoth languages use the Thread Synchronization and SafetyC# uses the lock (object)
{
/* code to be synchronized */
}
PointersJava does not support pointers. A major problem with using pointers in C# is that there is a background automatic garbage collection process in operation. Trying to free memory, garbage collection could change the memory location of a current object without the programmer’s knowledge. So any pointer which previously pointed to that object will no longer do so. This could compromise the running of the C# program and could affect the integrity of other programs. Therefore the code using pointers has to be explicitly marked by the programmer as
StructuresC# supports structures which are value types and is allocated once declared. It is an error to create a parameter-less constructor for a PropertiesProperty combines a field with the methods that access it. It consists of a name along with <return type> name
{
get { /* get accessor code */ }
set { /* set accessor code */ }
}
AttributesC# allows addition of declarative information to the program in the form of an attribute. An attribute defines additional information associated with a class, structure or a method. It is not a member of a class and it only specifies additional information that is attached to an item. Java too has a well developed API that supports attributes. DelegatesDelegate is an object that can refer to a method, and that method can be invoked through this reference. The same delegate can be used to invoke different methods during runtime by simply changing the method to which the delegate refers. delegate <return_type> <delegate_name> (parameter list);
EventsAn event is an automatic notification that some action has occurred. An object that has an interest in an event registers an event handler for that event. When the event occurs, all registered handlers are called. Both Java and C# support event handling. In C#, event handlers are represented by delegates. event <event_delegate> object;
Files and StreamsIn both C# and Java, I/O and file handling operations are implemented using streams. SerializationSerialization is the mechanism used by the .NET environment to support streaming of user-defined types. It allows you to read and write objects through a stream such as file. It is also known as Object Persistence because it retains the state of the object when it is in some form of storage or when it is transferred from one place to another. Serialization is the best means of transferring the representation of a class in an automatic and seamless manner. Serializable objects in C# are specified with the
Serialization of objects can also be customized using the Operator OverloadingJava does not provide for operator overloading, whereas C# like in C++ supports operator overloading. ConclusionBoth Java and C# with their well developed APIs, are extremely competent programming languages in their own right, and have revolutionized the world of programming. Competition between C# and Java is one of the best things that has happened to the software industry in a long time. C# being the latest one has had the chance to rectify certain shortcomings of Java, while Java has the advantage of being the already established language. The ultimate result has been better programming practices and hence better applications. The programmer now has an option to choose from the rich set of features available in Java or .NET platforms according to his needs. The Visual Studio IDE is an outstanding piece of work and will go a long way in increasing the popularity of .NET technology. One can confidently say that completely unseating Java and replacing it with .NET would be an uphill task. But C# takes the best from the past and incorporates the latest and the best in modern computer language design, hence carving a niche for itself as one of the best programming languages ever. ReferencesBooks:
Web Sources: | ||||||||||||||||||||