跳转到内容

比較C♯和Java

维基百科,自由的百科全书

这是本页的一个历史版本,由(www itshixun com)GaoXiaoZu留言 | 贡献2009年5月1日 (五) 02:09 (新条目)编辑。这可能和当前版本存在着巨大的差异。

(差异) ←上一修订 | 最后版本 (差异) | 下一修订→ (差异)

Template:Pound

Template:ProgLangCompare This is a comparison of the C# programming language with the Java programming language. As the two are both garbage-collected runtime-compiled languages with syntax derived from C and C++, there are many similarities between Java and C#. However, there are also many differences, with C# being described as a hybrid of C++ and Java, with additional new features and changes. This page documents the strong general similarities of the languages and then points out those instances where the languages differ.

Language

Object handling

Both C# and also Java are designed from the ground up as object oriented languages using dynamic dispatch, with a syntax similar to C++. (C++ in turn is derived from C.) Neither language is a superset of C or C++, however. Both use garbage collection as a means of reclaiming memory resources, rather than explicit deallocation of memory. Both include thread synchronization mechanisms as part of their language syntax.

References

C# allows restricted use of pointers. Pointers and pointer-arithmetic are potentially unsafe in a managed environment as they can be used to bypass the strict rules for object access. C# addresses that concern by requiring that code blocks or methods that use the feature be marked with the unsafe keyword, so that all clients of such code can be aware that the code may be less secure than otherwise. The compiler requires the /unsafe switch to allow compilation of a program that uses such code. Generally, unsafe code is either used to allow better interoperability with unmanaged APIs or system calls (which are inherently "unsafe"), or for performance reasons. Java does not allow pointers or pointer-arithmetic to be used.

Data types

Both languages support the idea of primitive types (all of which, except for String, are value types in C#/.NET). C# has more primitive types than Java, with unsigned as well as signed integer types being supported, and a decimal type for decimal floating-point calculations. Java lacks unsigned types. In particular, Java lacks a primitive type for an unsigned byte, while C# bytes are unsigned by default. Strings are treated as (immutable) objects in both languages, but support for string literals provides a specialized means of constructing them. C# also allows verbatim strings for quotation without escape sequences, which also allow newlines.

Both allow automatic boxing and unboxing to translate primitive data to and from their object form. Effectively, this makes the primitive types a subtype of the Object type. In C# this also means that primitive types can define methods, such as an override of Object's ToString() method. In Java, separate primitive wrapper classes provide such functionality. In Java primitive values are not implicitly boxed when dereferenced and an explicit cast is required for an instance call on a primitive value ((Integer)42).toString() instead of a C# instance call 42.ToString(). Another difference is that Java makes heavy use of boxed types in generics (see below), and as such allows an implicit unboxing conversion (in C# this requires a cast). As these implicit unboxing conversions can potentially throw null pointer exceptions, modern integrated development environments and compilers can be configured to highlight them.

Value types

C# allows the programmer to create user-defined value types, using the struct keyword. From the programmer's perspective, they can be seen as lightweight classes. Unlike regular classes, and like the standard primitives, such value types are allocated on the stack rather than on the heap. They can also be part of an object (either as a field or boxed), or stored in an array, without the memory indirection that normally exists for class types. Structs also come with a number of limitations. Because structs have no notion of a null value and can be used in arrays without initialization, they always come with an implicit default constructor that essentially fills the struct memory space with zeroes. The programmer can only define additional constructors with one or more arguments. This also means that structs lack a virtual method table, and because of that (and the fixed memory footprint), they cannot allow inheritance (but can implement interfaces).

Enumerations

Enumerations in C# are derived from a primitive 8, 16, 32, or 64 bit integer type. Any value of the underlying primitive type is a valid value of the enumeration type, though an explicit cast may be needed to assign it. C# also supports bitmapped enumerations where an actual value may be a combination of enumerated values bitwise or'ed together. Enumerations in Java, on the other hand, are objects. The only valid values in a Java enumeration are the ones listed in the enumeration. As objects, each enumeration can contain its own fields which can be modified. Special enumeration set and map collections provide fully type-safe functionality with minimal overhead. Java enumerations allow differing method implementations for each value in the enumeration. Both C# and Java enumerations can be converted to strings and can be used in a switch statement.

Arrays

Array and collection types are also given significance in the syntax of both languages, thanks to an iterator-based foreach statement loop. In C# an array corresponds to an object of the Array class, while in Java each array is a direct subclass of the Object class (but can be cast to an array of an element type that is an ancestor of its true element type), and does not implement any of the collection interfaces. C# has true multidimensional arrays, as well as the arrays-of-arrays that are available in Java (and which in C# are commonly called jagged arrays). Multidimensional arrays can in some cases increase performance because of increased locality (as there is a single pointer dereference, instead of one for every dimension of the array as is the case for jagged arrays). Another advantage is that the entire multidimensional array can be allocated with a single application of operator new, while jagged arrays require loops and allocations for every dimension. Note, though, that Java provides a syntactic construct for allocating a multidimensional jagged array with regular lengths (a rectangular array in the C# terminology); the loops and multiple allocations are then performed by the virtual machine and need not be explicit at the source level.

Inner classes

Both languages allow inner classes, where a class is defined entirely within another class. In Java, these classes have access to both the static and non-static members of the outer class (unless the inner class is declared static, then it only has access to the static members). Local classes can be defined within a method and have access to the method's local variables declared final, and anonymous local classes allow the creation of class instances that override some of their class methods.

C# also provides inner classes, but unlike Java, requires an explicit reference to the outer class to its non-static members. Also, C# provides anonymous delegates as a construct that can provide access to local variables and members (see Event handling). Local classes and anonymous classes are not available.

Partial classes

C# allows a class definition to be split across several source files using a feature called partial classes. Each part must be marked with the keyword partial. All the parts must be presented to the compiler as part of a single compilation. Parts can reference members from other parts. Parts can implement interfaces and one part can define a base class. The feature is useful in code generation scenarios where a code generator can supply one part and the developer another part to be compiled together. The developer can thus edit their part without the risk of a code generator overwriting that code at some later time. Unlike the class extension mechanism a partial class allows "circular" dependencies amongst its parts as they are guaranteed to be resolved at compile time. Java has no corresponding concept.

Generics

Both languages now support generics programming, but they have taken different paths to its implementation.

Generics in Java are a language-only construction; they are implemented only in the compiler. The generated classfiles include generic signatures only in the form of metadata (allowing the compiler to compile new classes against them). The runtime has no knowledge of the generic type system, which meant that JVM implementations only needed minimal updates to handle the new class format.

To achieve this goal the compiler replaces all generic types by their upper bounds and inserts casts appropriately in the various places where the type is used. The resulting byte code will contain no references to any generic types or parameters. This technique of implementing generics is known as type erasure. This means that runtime information about the actual types is not available at runtime, and imposes some restrictions such as the inability to create new instances or arrays of generic type arguments. (See also Generics in Java.)

C# took a different route. Support for genericity was integrated into the virtual execution system itself and first appeared in .NET 2.0. The language then becomes merely a front-end for the underlying generics support in the execution system. As in Java, the compiler provides static type safety checking, but additionally the JIT performs load time verification of the correctness. Information on generic types is fully preserved at runtime, and allows complete reflection support as well as instantiation of generic types.

Java does not allow to specialize generic classes with primitive types, while C# allows generics for both reference types and value types, including primitive types. Java instead allows the use of boxed types as type parameters (e.g., List<Integer> instead of List<int>), but this comes at a cost since all such values need to be heap-allocated. In both Java and C#, generic specializations that use different reference types share equivalent underlying code,[1] but for C# the Common Language Runtime (CLR) dynamically generates optimized code for specializations on value types.

Notation and special features

Special feature keywords

keyword feature, example usage
checked, unchecked In C#, checked statement blocks or expressions can enable run-time checking for arithmetic overflow.
get, set C# implements properties as part of the language syntax with their optional corresponding get and set accessors, as an alternative for the accessor methods used in Java, which is not a language feature but a coding pattern based on method name conventions.
goto C# supports the goto keyword. This can occasionally be useful, for example for implementing finite state machines or for generated code, but the use of a more structured method of control flow is usually recommended (see criticism of the goto statement). Java allows labeled breaks and continues, which make up for many of the uses of goto.
switch(color)
{
    case Color.Blue:
         Console.WriteLine("Color is blue"); break;
    case Color.DarkBlue:
         Console.WriteLine("Color is dark");
         goto case Color.Blue;
    // ...
}
out, ref C# has support for output and reference parameters. These allow returning multiple output values from a method, or passing values by reference.
strictfp Java uses strictfp to guarantee the results of floating point operations remain the same across platforms.
switch In C#, the switch statement also operates on strings and longs but only allows fallthrough for empty statements. Java switch statement does not operate on strings nor long primitive type but falls through for all statements (excluding those with 'break').
throws Java requires every method to declare the checked exceptions or superclasses of the checked exceptions that it can throw. Any method can also optionally declare the unchecked exception that it throws. C# has no such syntax.
public int readItem() throws java.io.IOException
{
    // ...
}
using C#'s using causes the Dispose method (implemented via the IDisposable interface) of the object declared to be executed after the code block has run or when an exception is thrown within the code block.
// Create a small file "test.txt", write a string, 
// ... and close it (even if an exception occurs)
using (StreamWriter file = new StreamWriter("test.txt"))
{
    file.Write("test");
}
yield C# allows the use of the yield keyword to express iterator generators. In Java, iterators can be defined only using (possibly anonymous) classes, requiring considerably more boilerplate code. Below is an example of an iterator that takes an iterable input (possibly an array) and returns all even numbers.
public static IEnumerable<int> GetEven(IEnumerable<int> numbers)
{
    foreach (int i in numbers)
    {
        if (i % 2 == 0)
            yield return i;
    }
}

Callbacks and Event handling

C# implements object oriented method pointers in the form of delegates. A delegate is a special type which can capture a reference to an instance or static method if its signature is compatible. Multicast-delegates are called events (see below). Delegates provide support for event-driven programming. They are type-safe references to methods and can be combined to allow multicasting. To support them there is a special syntax to define events in classes and operators to register, unregister or combine event handlers. Delegates support covariance and contravariance, and can be created as anonymous methods with full-featured closure semantics. In .NET, closures and anonymous delegates are syntactic sugar.[2][3]

Java does not have a language-level construct like the C# delegate. The observer[4] pattern is used for event-driven programming in Java. Anonymous inner classes are commonly used to implement the listener, allowing you to define the body of the class and create an instance of it in a single point in the code. Java anonymous classes has been seen by some as syntactic sugar, and to be more verbose than C# delegates.[來源請求]

Numeric applications

To adequately support applications in the field of mathematic and financial computation, several language features exist.[5] In this category, Java provides the strictfp keyword, that enables strict floating-point calculations for a region of code. This will ensure that calculations return the exact same result on all platforms. C# provides no equivalent, but does provide the built-in decimal type, for accurate decimal floating-point calculations. This forgoes the problems that exist with binary floating-point representations (float, double). Such binary representations are not suited to accurately represent decimal numbers and hence introduce rounding errors. For financial applications, an accurate decimal type is essential.

The BigDecimal class also provides such characteristics for Java. BigDecimal and BigInteger are types provided with Java that allow arbitrary-precision representation of numbers. The current release of the .NET framework (3.5) does not currently include such classes, although third party implementations exist (see Arbitrary-precision arithmetic).

In Java there is no way to provide the same level of integration for library-defined types such as BigDecimal or complex numbers as there is for the primitive types. For this purpose, C# provides the following:

  • Operator overloading and indexers providing convenient syntax (see below).
  • Implicit and explicit conversions; allow conversions such as exist for the built-in int type that can implicitly convert to long.
  • Valuetypes and generics based on valuetypes; in Java every custom type must be allocated on the heap, which is detrimental for performance of both custom types and collections.

In addition to this, C# can help mathematic applications with the checked and unchecked operators that allow to enable or disable run-time checking for arithmetic overflow for a region of code. It also offers rectangular arrays, that have advantages over regular nested arrays for certain applications.[5]

Operator overloading

C# includes a large number of notational conveniences over Java, many of which, such as operator overloading and user-defined casts, are already familiar to the large community of C++ programmers. It also has "Explicit Member Implementation" which allows a class to specifically implement methods of an interface, separate to its own class methods, or to provide different implementations for two methods with the same name and signature inherited from two base interfaces.

C# includes indexers which can be considered a special case of operator overloading (like C++ operator[]), or parametrized get/set properties. An indexer is a property named this[] which uses one or more parameters (indexes); the indexes can be objects of any type:

myList[4] = 5;
string name = xmlNode.Attributes["name"];
orders = customerMap[theCustomer];

Java does not include operator overloading in order to prevent abuse of the feature, and to keep the language simpler.[6] C# allows operator overloading (subject to certain restrictions to ensure logical coherence), which, when used carefully, can make code succinct and more readable.

Methods

Methods in C# are non-virtual by default, and have to be declared virtual explicitly if desired. In Java, all non-static non-private methods are virtual. Virtuality guarantees that the most recent override for the method will always be called, but incurs a certain runtime cost on invocation as these invocations cannot be normally inlined, and require an indirect call via the virtual method table. However, some JVM implementations, including the Sun reference implementation, implement inlining of the most commonly called virtual methods.

In Java methods are virtual by default (although they can be "sealed" by using the final modifier to disallow overriding). There is no way to let derived classes define a new, unrelated method with the same name. This can be a problem when a base class is designed by a different person, and a new version introduces a method with the same name and signature as some method already present in the derived class. In Java, this will mean that the method in the derived class will implicitly override the method in the base class, even though that was not the intent of the designers of either class. To prevent this versioning problem, C# requires explicit declaration of intent when overriding virtual methods in a derived class. If a method should be overridden, the override modifier must be specified. If overriding is not desired, and the class designer merely wishes to introduce a new method shadowing the old one, the new keyword must be specified. The new and override keywords also avoid the problem which can arise from a base class being extended with a protected/public method whose signature is already in use by a derived class. In Java a recompilation will lead the compiler to regard the method of the derived class as an override of the method of the base class, which was probably not the intent of the base class developer. The C# compiler will regard the method as if new had been specified, but will issue a warning to that effect. To partially accommodate for these versioning problems, Java 5.0 introduced the @Override annotation, but to preserve backwards compatibility it could not be made compulsory, so it cannot prevent the above accidental overriding situation. Like the override keyword in C#, it can however help ensure that a method in the base class with the same signature exists and is correctly overridden.

Explicit interface implementation

If a method (or property in C#) is specified with the same name and signature in multiple interfaces, the members will clash when a class is designed which implements those interfaces. An implementation will by default implement a common method for all of the interfaces. If separate implementations are required (because the methods really do serve separate purposes, or because return values differ between the interfaces) C# explicit interface implementation will solve the problem. In Java there is no way to solve this problem other than to refactor one or more of the interfaces to avoid name clashes. C# explicit implementation will also hide the method from the primary class interface, and can thus help reduce the class interface complexity.

Closures

When a reference to a method can be passed around for later execution, a problem arises about what to do when the method has references to variables/parameters in its lexical scope. C# has true closures in which the referenced method can fully capture any variable/parameter from its lexical scope. In Javas anonymous inner classes only references to final members of the lexical scope are allowed, thus requiring the developer to artificially introduce extra levels of indirections and boxing primitive types if he wants to reference and update those from the inner class.

Closures have also been proposed as a new feature for Java SE 7.[7] Like delegates in C#, such closures would have full access to all local variables in scope, not just read-only access to those marked final (as with anonymous inner classes). They are being discussed for inclusion in Java 7. No decision has been taken yet.

Lambdas and expression trees

C# also features a special type of inline closures called lambdas. These are not methods as they cannot form part of a class interface; they are more in the realm of functional programming. On top of that lambda functions can double as a way to define special data structures called expression trees. Whether they are seen as an executable function or a data structure depends on compiler type inference and what type of variable or parameter they are assigned/cast to. Lambdas and expression trees play key roles in LINQ. Java does not feature lambdas or expression trees; its primary mechanism for inline scope capture and method definition is the anonymous inner class syntax.

Partial methods

Related to partial classes C# allows partial methods to be specified within partial classes. A partial method is an intentional declaration of a method with a number of restrictions on the signature. These restrictions ensure that if a definition is not actually provided by any class part, then the method and every call to it can be safely erased. This feature allows code to provide a large number of interception points (like the template method GoF design pattern) without paying any runtime overhead if these extension points are not being used by another class part at compile time. Java has no corresponding concept.

Extension methods

Using a special this designator on the first parameter of a method, C# allows the method to act as if it were a member method of the type of the first parameter. This extension of the foreign class is purely syntactical. The extension method needs to be static and defined within a purely static class. It must obey any restriction on such external static methods and thus cannot break object encapsulation. The "extension" is only active within scopes where the namespace of the static host class has been imported. In Java, the same effect can be done with a regular method of another class, but the syntax will be that of a function call as oppossed to the method call-like syntax of C# extensions.

Generator methods

A C# method which is declared as returning IEnumerable, IEnumerator or the generic versions of these interfaces, can be implemented using yield syntax. This is a form of limited, compiler-generated continuations and can drastically reduce the code required to traverse or generate sequences; although that code is just generated by the compiler instead. The feature can also be used to implement infinite sequences, such as a the sequence of fibonacci numbers. Java has no corresponding concept.

Conditional compilation

Unlike Java, C# implements conditional compilation using preprocessor directives. It also provides a Conditional attribute to define methods that are only called when a given compilation constant is defined. This way, assertions can be provided as a framework feature with the method Debug.Assert(), which is only evaluated when the DEBUG constant is defined. Since version 1.4, Java provides a language feature for assertions, which are turned off at runtime by default but can be enabled using the "-enableassertions" or "-ea" switch when invoking the JVM.

Namespaces and source files

C#'s namespaces are similar to those in C++. Unlike package names in Java, a namespace is not in any way tied to location of the source file. While it's not strictly necessary for a Java source file location to mirror its package directory structure, it is the conventional organization.

Both languages allow importing of classes (e.g., import java.util.* in Java), allowing a class to be referenced using only its name. Sometimes classes with the same name exist in multiple namespaces or packages. Such classes can be referenced by using fully qualified names, or by importing only selected classes with different names. To do this, Java allows importing a single class (e.g., import java.util.List). C# allows importing classes under a new local name using the following syntax: using Console = System.Console. It also allows importing specializations of classes in the form of using IntList = System.Collections.Generic.List<int>.

Java has a static import syntax that allows using the short name of some or all of the static methods/fields in a class (e.g., allowing foo(bar) where foo() can be statically imported from another class). C# has a static class syntax (not to be confused with static inner classes in Java), which restricts a class to only contain static methods. C# 3.0 introduces extension methods to allow users to statically add a method to a type (e.g., allowing foo.bar() where bar() can be an imported extension method working on the type of foo).

The Sun Microsystems Java compiler requires that a source file name must match the only public class inside it, while C# allows multiple public classes in the same file, and puts no restrictions on the file name. C# 2.0 and later allows a class definition to be split into several files, by using the partial keyword in the source code.

Exception handling

Java supports checked exceptions (in addition to unchecked exceptions). C# only supports unchecked exceptions. Checked exceptions force the programmer to either declare the exception thrown in a method, or to catch the thrown exception using a try-catch clause.

Checked exceptions can be helpful for good programming practice, ensuring that all errors are dealt with. However Anders Hejlsberg, chief C# language architect, and others argue that they were to some extent an experiment in Java and that they haven't been shown to be worthwhile except for in small example programs.[8][9]

One criticism is that checked exceptions encourage programmers to use an empty catch block, which silently eats exceptions rather than letting the exceptions propagate to a higher-level exception-handling routine: catch (Exception e) {}. Another criticism of checked exceptions is that a new implementation of a method may cause unanticipated checked exceptions to be thrown, which is a contract-breaking change. This can happen in methods implementing an interface that only declares limited exceptions, or when the underlying implementation of a method changes. To allow for such unanticipated exceptions to be thrown, some programmers simply declare the method can throw any type of exception ("throws Exception"), which defeats the purpose of checked exceptions. In some cases however, exception chaining can be applied instead; re-throwing the exception in a wrapper exception. For example, if an object is changed to access a database instead of a file, an SQLException could be caught and re-thrown as an IOException, since the caller may not need to know the inner workings of the object.

There are also differences between the two languages in treating the try-finally statement. The finally is always executed, even if the try block contains control-passing statements like throw or return. In Java, this may result in unexpected behavior if the try block is left by a return statement with some value, and then the finally block that is executed afterwards is also left by a return statement with a different value. C# resolves this problem by prohibiting any control-passing statements like return or break in the finally block.

A common reason for using try-finally blocks is to guard resource managing code, so that precious resources are guaranteed to be released in the finally block. C# features the using statement as a syntactic shorthand for this common scenario, in which the Dispose() method of the object of the using is always called.

Finally Blocks and Uncaught Exceptions

A significant difference between Java and C# is over the question of whether finally blocks should execute in response to an unhandled exception. Both languages allow a program to disregard some exceptions. In C#, any exception type may be uncaught. In Java descendents of RuntimeException, such as NullPointerException, need not be declared and therefore need not be caught, as they indicate a bug.

The ECMA standard for the CLI (from which C# derives its exception features) states that exceptions are handled in a two-pass search of the stack.[10] The first pass attempts to locate a matching catch block, and terminates the program if none is found. Only if a matching catch block is found does the second pass execute, which runs the intervening finally blocks. This allows the problem to be diagnosed without the program state first being modified by the finally blocks; it also eliminates the risk that finally blocks may have undesirable side-effects when the program is in an unknown state (such as corruption of external data, or throwing further exceptions).

The Java Language Specification states that finally blocks run even if an exception is uncaught, and gives a code example showing the expected output.[11]

Lower level code

The Java Native Interface (JNI) feature allows Java programs to call non-Java code. However, JNI does require the code to be called to follow several conventions and impose restrictions on types and names used. This means that an extra adaption layer between legacy code and Java is often needed. This adaption code must be coded in a non-Java language, often C or C++. JNA allows easier calling of native code that only requires writing Java code, but comes at a performance cost.

In addition, third party libraries provide for Java-COM bridging, e.g. JACOB (free), and J-Integra for COM (proprietary).

.NET Platform Invoke (P/Invoke) offers the same capability by allowing calls from C# to what Microsoft refers to as unmanaged code. Through metadata attributes the programmer can control exactly how the parameters and results are marshalled, thus avoiding the need for extra adaption code. P/Invoke allows almost complete access to procedural APIs (such as Win32 or POSIX), but limited access to C++ class libraries.

In addition, .NET Framework also provides a .NET-COM bridge, allowing access to COM components as if they were native .NET objects.

C# also allows the programmer to disable the normal type-checking and other safety features of the CLR, which then enables the use of pointer variables. When this feature is used, the programmer must mark the code using the unsafe keyword. JNI, P/Invoke, and "unsafe" code are equally risky features, exposing possible security holes and application instability. An advantage of unsafe, managed code over P/Invoke or JNI is that it allows the programmer to continue to work in the familiar C# environment to accomplish some tasks that otherwise would require calling out to unmanaged code. A program or assembly using unsafe code must be compiled with a special switch and will be marked as such. This enables runtime environments to take special precautions before executing potentially harmful code.

Language history and evolution

Java

Java is older than C# and has built up a large and highly active user base, becoming the lingua franca in many modern branches of computer science, particularly areas which involve networking.[來源請求] Java dominates programming courses at high school and college level in the United States, and there are currently more Java than C# books.[12] Java's maturity and popularity have ensured more third party Java API and libraries (many of them open source)[來源請求] than C#.

An occasionally voiced criticism [13] of the Java language is that it evolves slowly, lacking some features which make fashionable programming patterns and methodologies easier.[來源請求] Some critics [谁?] argue the designers of C# are perhaps too quick to pander to current trends in programming, thus lacking focus and simplicity.[來源請求] Java's designers seem [原創研究?] to have taken a more conservative stand on adding major new features to their language syntax than other current languages, perhaps [谁?] not wanting to tie the language too tightly with trends which may prove to be dead ends.

These trends [原創研究?] have been broken with the Java 5.0 release, which introduced several new major language features: a foreach construct, autoboxing, methods with variable number of parameters (varargs), enumerated types, generic types, and annotations. With the exception of Generics, C# included all these features from its beginning, some under different names.[14] Proposals and specifications for the new features had been worked on in the Java community for considerable time before they were introduced. Indeed, some had been in gestation since before C#'s initial release (e.g., work on Generics formally began in May 1999[15]) such was the Java community's conservatism at that time.

Problem-specific language additions to Java have been considered and, for now at least, rejected. This approach, along with a number of other new languages and technologies that address themselves specifically towards current programming trends, has sparked a renewed debate within the Java camp about the future direction of the Java language and whether its 'conservative evolution' is right.[來源請求]

As of 2008, there is an ongoing debate with the inclusion of closures[16] and properties[17] into the language syntax for Java 7.

C#

By contrast, C# is a relatively new language. Microsoft has studied existing languages such as Java and Object Pascal, and has changed some aspects of the language and runtime environment in response to perceived failures and difficulties with its predecessors. C# accommodates constructs more commonly found in languages such as C++, Delphi (designing which was Anders Hejlsberg's principal job when he was at Borland), and, in recent C# versions, borrows from dynamic scripting languages such as Ruby.

C# has evolved rapidly to attempt to streamline development for problem-specific features. C# 3.0 adds SQL-like language integrated queries suited for querying data from collections, databases or XML documents. It however builds upon general-purpose language features; lambda expressions and extension methods features, that also allow such queries to be expressed and optimized for user types.

Before creating C#, Microsoft implemented a modified Java environment, called J++, adding new features in a manner which was in direct contravention to the standards and conventions ensuring the platform neutrality which lies at the heart of Java. This violated the license agreement Microsoft had signed, requiring that standards and specifications be strictly adhered to in return for using the Java name and brand logos. Sun Microsystems sued, and in settling the suit, Microsoft agreed to discontinue J++ (other existing Microsoft products that used Java were permited to continue such use for seven years)[18]. With the release of the .NET framework (and C#), the project was revived in the form of J#.

See also

References