Why does C# include programming constructs that are not CLS-compliant? - c#

It seems strange that the flagship language of .NET would include programming constructs that are not CLS-compliant. Why is that?
Example (from here): Two or more public / protected / protected internal members defined with only case difference
public int intA = 0;
public int INTA = 2;
or
public int x = 0;
public void X()
{
}

Even unsigned integers aren't compliant (at least, on the public API), yet they are very important to people who do bit-shifting, in particular when right-shifting (signed and unsigned have different right-shift behaviours).
They are ultimately there to give you the freedom to use them when appropriate. The case-sensitivity one I could get less religious about - despite the convenience of having a field and property differ only by case, I think I could live happily with being forced to use a different name! Especially now we have automatically implemented properties...
This is similar to how it lets you use unsafe - the difference here being that a few unsigned integers aren't going to destabilise the entire runtime, so they don't need quite as strong molly-guards.
You can add:
[assembly: CLSCompliant(true)]
if you like, and the compiler will tell you when you get it wrong.
And finally: most code (by volume) is not consumed as a component. It is written to do a job, and maybe consumed by other code in-house. It is mainly library writers / vendors that need to worry about things like CLS compliance. That is (by the numbers) the minority.

That's not how CLS compliance works. It is something that's your burden. C# doesn't restrain itself to strict compliancy itself, that would make it a language with poor expressivity. Dragging all .NET languages down to the lowest common denominator would have quickly killed the platform as a viable programming environment.
It is up to you to ensure that the publicly visible types in your assembly meet CLS compliancy. Making sure that class members don't differ only by case is very simple to do. Let the compiler help you out by using the [assembly:CLSCompliant(true)] attribute and the compiler will warn you when you slipped.

See http://msdn.microsoft.com/en-us/library/bhc3fa7f.aspx.
CLS is a specification that one opts-in to. Quote from above:
When you design your own CLS-compliant components, it is helpful to use a CLS-compliant tool. Writing CLS-compliant components without this support is more difficult because otherwise you might not have access to all the CLS features you want to use.
Some CLS-compliant language compilers, such as the C# or Visual Basic compilers, enable you to specify that you intend your code to be CLS-compliant. These compilers can check for CLS compliance and let you know when your code uses functionality that is not supported by the CLS. The C# and Visual Basic compilers allow you to mark a program element as CLS-compliant, which will cause the compiler to generate a compile-time error if the code is not CLS-compliant. For example, the following code generates a compiler warning.
Example code from above link:
using System;
// Assembly marked as compliant.
[assembly: CLSCompliant(true)]
// Class marked as compliant.
[CLSCompliant(true)]
public class MyCompliantClass {
// ChangeValue exposes UInt32, which is not in CLS.
// A compile-time warning results.
public void ChangeValue(UInt32 value){ }
public static void Main( ) {
int i = 2;
Console.WriteLine(i);
}
}
This code generates the following C# warning:
Copy warning CS3001: Argument type 'uint' is not CLS-compliant

My two cents about CLS Compliance
The .net languages are all evolutions of languages that were in existence at the time it was created. The languages were crafted so that you could easily convert the base projects into .Net projects without too much development effort. Due to the vast differences between the languages there needed to be some sort of convention for the languages to talk with each other. Take the language examples below:
VB.Net is a language that is derived from the earlier language VB6. It's suppose to be very similar in style to VB6 and as such takes alot of the conventions VB6 used. Since VB6 was suppose to be easy to learn/use by non developers it has certain characteristics that make it more idiot proof. Dynamic typing, case insensitivity being two of these things.
C#.Net/C++.Net are derivatives of the more programmer friendly C++. Since they're an evolution of this language it has things in it that C++ would let you do. Case sensitivity, static typing etc.
Now when faced with two dissimilar languages that they wanted to make interoperable Microsoft did the only reasonable thing. They made restrictions on how the two languages can interact with each other through the use of the basically a software contract. This code can be used in only this way because of the differences in the languages.
For example take VB.Net code calling C# code
If the C# code had two functions that differed only in case, X() vs x(), VB.net would never be able to call this code correctly since it is case insensitive. The CLS compliance has to make this illegal. If you look at the other rules they're basically doing the same thing for other language features between the different languages.

I would guess the case insensitivity was only included in CLS compliance so that VB.NET could be CLS compliant. From what I understand, there is no issue if a particular language construct is not CLS compliant unless you are using it in such a way that the incompliant peices are available in the public API of your code.
The hint from Microsoft would seem to be that CLS compliance is only important in code that you are accessing from different languages (such as referencing a C# assembly from a VB.NET project).

I think Microsoft wanted to give developers freedom. No constraints if not necessary. C# is not restricted by CLS because not everyone needs interoperability with VB.

If there was universal agreement about what features should be included in a programming language, the world would only need one programming language (which would include precisely those features everyone agreed should be there). Of course, in reality some people will regard as important features which others don't care about (or even find distasteful). The CLS standard essentially does three things:
It says that certain features are so important that any language which does not include them should be considered inadequate for general-purpose .net programming.
It says that programmers whose libraries don't require any features other than those listed should expect that their libraries will be usable by programmers using any language that is suitable for general-purpose .net programming.
It informs programmers that if parts of their libraries would require the use of features which languages are not required to support, those parts might not be usable in languages which are suitable for .net programming, but don't include the required features.
When languages like vb.net or C# allow the creation of non-CLS compliant programming, what that means is that Microsoft decided that certain features were useful enough to justify inclusion in those languages, but not so wonderful or noncontroversial as to justify mandating all languages include them.

Related

Getting "Argument type 'StreamSocket' is not CLS-compliant" warning on build

I'm developing a UWP library which has public properties and method parameters of StreamSocket class. However, I'm getting "StreamSocket is not CLS-compliant" warning. What's so special there that Microsoft decided to leave the respective assembly non-CLS-compliant and are there any potential issues I should know about when using/distributing this library? Maybe CLS incompliance will somehow limit the ways my library can be used by other developers?
Well, from the documentation:
If you design a CLS–compliant class library, your library will have a guarantee of interoperability with a wide range of programming languages; therefore, your library is likely to have a wider customer base than a version that is not CLS-compliant.
So the [obvious] answer is that they did not have "programming language interoperatibility" in mind when they coded that thing.
I am not surprised to be honest, MS is not exactly known for strictness (IE anyone?)
Read more here: https://msdn.microsoft.com/en-us/library/bhc3fa7f.aspx
UPDATE:
I will try to demystify this a little bit based on the comments.
The CLS (Common Language Specification) defines the features that any language that targets the .NET Framework MUST support. Hence, you should only care about it if your libraries are going to be consumed by a .NET language.
For instance, there is a restriction in the CLS that says that class and member names cannot differ only by case. You can't have one property named MySocket and another one named mySocket. This is important for languages like VB .NET which are not case sensitive.
In the case at hand, your library is exposing StreamSocket, which is not marked as CLS Compliant. What if this class has methods like the samples above and you try to use your library in some VB.NET project? This is what the compiler is warning you about.

Aliases and dot net types and c# types

When I use resharper tool, it just says "use built-in type "string" rather than using "String". Similarly, it converts UInt32 to just uint.
I have googled this and all I can find is they are aliases. Aliases meaning "Duplicates". Ok.
But, what exactly do they mean about it ?
When both are same, why the tool suggests using "string" and "uint" for "String" and "UInt32" ?
Also, what is the difference between dot-net types and C# types.
Have googled it but couldnt find any satisfying answers.
Thanks.
The answer given by Rafal sums it up, but there are a couple of clarifications I'd like to make: the only case when using keywords rather than type names is necessary is when defining an enum's underlying type -- In that case, using the latter would not be allowed.
Example:
enum Foo : Int32
{
}
The above won't compile.
Also, while I generally prefer to use keywords, it must be said that while the types are the same for every language running on the .NET Framework, the keywords are different. For example, while in C# long is an alias for Int64, in C++/CLI, long is actually an Int32. That can create some confusion when, for instance, porting code between CLI languages.
String and string are same and so are the UInt32 and uint.
This just due to CLS-compliance, so that you could write C# class library and use in VB program and vice versa.
Some excerpts from MSDN:
To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, the Common Language Specification (CLS), which is a set of basic language features needed by many applications, has been defined. The CLS rules define a subset of the Common Type System; that is, all the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS. The CLS helps enhance and ensure language interoperability by defining a set of features that developers can rely on to be available in a wide variety of languages.
Please refer Common Language Specification
There is no difference between String and string because as you have pointed out those are aliases - alias is just a different name for the same thing.
As to why Resharper does something you should ask or seek on resharper dedicated site. In my opinion it is merely question of convention - you should use one of those and why not use the one that majority uses.

Best approach for designing F# libraries for use from both F# and C#

I am trying to design a library in F#. The library should be friendly for use from both F# and C#.
And this is where I'm stuck a little bit. I can make it F# friendly, or I can make it C# friendly, but the problem is how to make it friendly for both.
Here is an example. Imagine I have the following function in F#:
let compose (f: 'T -> 'TResult) (a : 'TResult -> unit) = f >> a
This is perfectly usable from F#:
let useComposeInFsharp() =
let composite = compose (fun item -> item.ToString) (fun item -> printfn "%A" item)
composite "foo"
composite "bar"
In C#, the compose function has the following signature:
FSharpFunc<T, Unit> compose<T, TResult>(FSharpFunc<T, TResult> f, FSharpFunc<TResult, Unit> a);
But of course, I don't want FSharpFunc in the signature, what I want is Func and Action instead, like this:
Action<T> compose2<T, TResult>(Func<T, TResult> f, Action<TResult> a);
To achieve this, I can create compose2 function like this:
let compose2 (f: Func<'T, 'TResult>) (a : Action<'TResult> ) =
new Action<'T>(f.Invoke >> a.Invoke)
Now, this is perfectly usable in C#:
void UseCompose2FromCs()
{
compose2((string s) => s.ToUpper(), Console.WriteLine);
}
But now we have a problem using compose2 from F#! Now I have to wrap all standard F# funs into Func and Action, like this:
let useCompose2InFsharp() =
let f = Func<_,_>(fun item -> item.ToString())
let a = Action<_>(fun item -> printfn "%A" item)
let composite2 = compose2 f a
composite2.Invoke "foo"
composite2.Invoke "bar"
The question: How can we achieve first-class experience for the library written in F# for both F# and C# users?
So far, I couldn't come up with anything better than these two approaches:
Two separate assemblies: one targeted to F# users, and the second to C# users.
One assembly but different namespaces: one for F# users, and the second for C# users.
For the first approach, I would do something like this:
Create a F# project, call it FooBarFs and compile it into FooBarFs.dll.
Target the library purely to F# users.
Hide everything unnecessary from the .fsi files.
Create another F# project, call if FooBarCs and compile it into FooFar.dll
Reuse the first F# project at the source level.
Create .fsi file which hides everything from that project.
Create .fsi file which exposes the library in C# way, using C# idioms for name, namespaces, etc.
Create wrappers that delegate to the core library, doing the conversion where necessary.
I think the second approach with the namespaces can be confusing to the users, but then you have one assembly.
The question: None of these are ideal, perhaps I am missing some kind of compiler flag/switch/attribute
or some kind of trick and there is a better way of doing this?
The question: has anyone else tried to achieve something similar and if so how did you do it?
EDIT: to clarify, the question is not only about functions and delegates but the overall experience of a C# user with an F# library. This includes namespaces, naming conventions, idioms and suchlike that are native to C#. Basically, a C# user shouldn't be able to detect that the library was authored in F#. And vice versa, an F# user should feel like dealing with a C# library.
EDIT 2:
I can see from the answers and comments so far that my question lacks the necessary depth,
perhaps mostly due to use of only one example where interoperability issues between F# and C#
arise, the issue of function values. I think this is the most obvious example and so this
led me to use it to ask the question, but by the same token gave the impression that this is
the only issue I am concerned with.
Let me provide more concrete examples. I have read through the most excellent
F# Component Design Guidelines
document (many thanks #gradbot for this!). The guidelines in the document, if used, do address
some of the issues but not all.
The document is split into two main parts: 1) guidelines for targeting F# users; and 2) guidelines for
targeting C# users. Nowhere does it even attempt to pretend that it is possible to have a uniform
approach, which exactly echoes my question: we can target F#, we can target C#, but what is the
practical solution for targeting both?
To remind, the goal is to have a library authored in F#, and which can be used idiomatically from
both F# and C# languages.
The keyword here is idiomatic. The issue is not the general interoperability where it is just possible
to use libraries in different languages.
Now to the examples, which I take straight from
F# Component Design Guidelines.
Modules+functions (F#) vs Namespaces+Types+functions
F#: Do use namespaces or modules to contain your types and modules.
The idiomatic use is to place functions in modules, e.g.:
// library
module Foo
let bar() = ...
let zoo() = ...
// Use from F#
open Foo
bar()
zoo()
C#: Do use namespaces, types and members as the primary organizational structure for your
components (as opposed to modules), for vanilla .NET APIs.
This is incompatible with the F# guideline, and the example would need
to be re-written to fit the C# users:
[<AbstractClass; Sealed>]
type Foo =
static member bar() = ...
static member zoo() = ...
By doing so though, we break the idiomatic use from F# because
we can no longer use bar and zoo without prefixing it with Foo.
Use of tuples
F#: Do use tuples when appropriate for return values.
C#: Avoid using tuples as return values in vanilla .NET APIs.
Async
F#: Do use Async for async programming at F# API boundaries.
C#: Do expose asynchronous operations using either the .NET asynchronous programming model
(BeginFoo, EndFoo), or as methods returning .NET tasks (Task), rather than as F# Async
objects.
Use of Option
F#: Consider using option values for return types instead of raising exceptions (for F#-facing code).
Consider using the TryGetValue pattern instead of returning F# option values (option) in vanilla
.NET APIs, and prefer method overloading over taking F# option values as arguments.
Discriminated unions
F#: Do use discriminated unions as an alternative to class hierarchies for creating tree-structured data
C#: no specific guidelines for this, but the concept of discriminated unions is foreign to C#
Curried functions
F#: curried functions are idiomatic for F#
C#: Do not use currying of parameters in vanilla .NET APIs.
Checking for null values
F#: this is not idiomatic for F#
C#: Consider checking for null values on vanilla .NET API boundaries.
Use of F# types list, map, set, etc
F#: it is idiomatic to use these in F#
C#: Consider using the .NET collection interface types IEnumerable and IDictionary
for parameters and return values in vanilla .NET APIs. (i.e. do not use F# list, map, set)
Function types (the obvious one)
F#: use of F# functions as values is idiomatic for F#, obviously
C#: Do use .NET delegate types in preference to F# function types in vanilla .NET APIs.
I think these should be sufficient to demonstrate the nature of my question.
Incidentally, the guidelines also have a partial answer:
... a common implementation strategy when developing higher-order
methods for vanilla .NET libraries is to author all the implementation using F# function types, and
then create the public API using delegates as a thin façade atop the actual F# implementation.
To summarise.
There is one definite answer: there are no compiler tricks that I missed.
As per the guidelines doc, it seems that authoring for F# first and then creating
a facade wrapper for .NET is a reasonable strategy.
The question then remains regarding the practical implementation of this:
Separate assemblies? or
Different namespaces?
If my interpretation is correct, Tomas suggests that using separate namespaces should
be sufficient, and should be an acceptable solution.
I think I will agree with that given that the choice of namespaces is such that it
does not surprise or confuse the .NET/C# users, which means that the namespace
for them should probably look like it is the primary namespace for them. The
F# users will have to take the burden of choosing F#-specific namespace.
For example:
FSharp.Foo.Bar -> namespace for F# facing the library
Foo.Bar -> namespace for .NET wrapper, idiomatic for C#
Daniel already explained how to define a C#-friendly version of the F# function that you wrote, so I'll add some higher-level comments. First of all, you should read the F# Component Design Guidelines (referenced already by gradbot). This is a document that explains how to design F# and .NET libraries using F# and it should answer many of your questions.
When using F#, there are basically two kinds of libraries you can write:
F# library is designed to be used only from F#, so it's public interface is written in a functional style (using F# function types, tuples, discriminated unions etc.)
.NET library is designed to be used from any .NET language (including C# and F#) and it typically follows .NET object-oriented style. This means that you'll expose most of the functionality as classes with method (and sometimes extension methods or static methods, but mostly the code should be written in the OO design).
In your question, you're asking how to expose function composition as a .NET library, but I think that functions like your compose are too low level concepts from the .NET library point of view. You can expose them as methods working with Func and Action, but that probably isn't how you would design a normal .NET library in the first place (perhaps you'd use the Builder pattern instead or something like that).
In some cases (i.e. when designing numerical libraries that do not really fit well with the .NET library style), it makes a good sense to design a library that mixes both F# and .NET styles in a single library. The best way to do this is to have normal F# (or normal .NET) API and then provide wrappers for natural use in the other style. The wrappers can be in a separate namespace (like MyLibrary.FSharp and MyLibrary).
In your example, you could leave the F# implementation in MyLibrary.FSharp and then add .NET (C#-friendly) wrappers (similar to code that Daniel posted) in the MyLibrary namespace as static method of some class. But again, .NET library would probably have more specific API than function composition.
You only have to wrap function values (partially-applied functions, etc) with Func or Action, the rest are converted automatically. For example:
type A(arg) =
member x.Invoke(f: Func<_,_>) = f.Invoke(arg)
let a = A(1)
a.Invoke(fun i -> i + 1)
So it makes sense to use Func/Action where applicable. Does this eliminate your concerns? I think your proposed solutions are overly-complicated. You can write your entire library in F# and use it pain-free from F# and C# (I do it all the time).
Also, F# is more flexible than C# in terms of interoperability so it's generally best to follow traditional .NET style when this is a concern.
EDIT
The work required to make two public interfaces in separate namespaces, I think, is only warranted when they are complementary or the F# functionality is not usable from C# (such as inlined functions, which depend on F#-specific metadata).
Taking your points in turn:
Module + let bindings and constructor-less type + static members appear exactly the same in C#, so go with modules if you can. You can use CompiledNameAttribute to give members C#-friendly names.
I may be wrong, but my guess is that the Component Guidelines were written prior to System.Tuple being added to the framework. (In earlier versions F# defined it's own tuple type.) It's since become more acceptable to use Tuple in a public interface for trivial types.
This is where I think you have do things the C# way because F# plays well with Task but C# doesn't play well with Async. You can use async internally then call Async.StartAsTask before returning from a public method.
Embrace of null may be the single biggest drawback when developing an API for use from C#. In the past, I tried all kinds of tricks to avoid considering null in internal F# code but, in the end, it was best to mark types with public constructors with [<AllowNullLiteral>] and check args for null. It's no worse than C# in this respect.
Discriminated unions are generally compiled to class hierarchies but always have a relatively friendly representation in C#. I would say, mark them with [<AllowNullLiteral>] and use them.
Curried functions produce function values, which shouldn't be used.
I found it was better to embrace null than to depend on it being caught at the public interface and ignore it internally. YMMV.
It makes a lot of sense to use list/map/set internally. They can all be exposed through the public interface as IEnumerable<_>. Also, seq, dict, and Seq.readonly are frequently useful.
See #6.
Which strategy you take depends on the type and size of your library but, in my experience, finding the sweet spot between F# and C# required less work—in the long run—than creating separate APIs.
Although it probably would be an overkill, you could consider writing an application using Mono.Cecil (it has awesome support on the mailing list) that would automate the conversion on the IL level. For example, you implement your assembly in F#, using the F#-style public API, then the tool would generate a C#-friendly wrapper over it.
For instance, in F# you would obviously use option<'T> (None, specifically) instead of using null like in C#. Writing a wrapper generator for this scenario should be fairly easy: the wrapper method would invoke the original method: if it's return value was Some x, then return x, otherwise return null.
You would need to handle the case when T is a value type, i.e. non-nullable; you would have to wrap the return value of the wrapper method into Nullable<T>, which makes it a bit painful.
Again, I'm quite certain that it would pay off to write such a tool in your scenario, maybe except if you'll be working on this such library (usable seamlessly from F# and C# both) regularly. In any case, I think it would be an interesting experiment, one that I might even explore sometime.
Draft F# Component Design Guidelines
(August 2010)
Overview This document looks at some of the issues related to F# component design and coding. In particular, it covers:
Guidelines for designing “vanilla” .NET libraries for use from any .NET language.
Guidelines for F#-to-F# libraries and F# implementation code.
Suggestions on coding conventions for F# implementation code

Any reason not to mark a DLL as CLSCompliant?

I am currently testing out Ndepend, and it gives me a warning that assemblies should be marked as CLSCompliant.
Our project is all C#, so it is not really needed.
What I am wondering is: are there any negative effects of marking a dll as clscompliant or should I just disable the warning?
Note I am not asking what CLSCompliant means that is covered here: What is the 'CLSCompliant' attribute in .NET?
This is one of those subtle cases... CLS compliance is probably of most importance to library authors, who can't control who the caller is. In your case, you state "our project is all C#", in which case you are right: it isn't needed. It adds restrictions (for example, on unsigned types) which might (or might not) affect representing your data in the most obvious way.
So: if it adds no value to you whatsoever, then frankly: turn that rule off. If you can add it for free (no code changes except the attributes), then maybe OK - but everything is a balance - effort vs result. If there is no gain here, don't invest time.
If you are a library author (merchant or OSS), then you should follow it.
There are several C# features that are not CLS compliant, for example unsigned types. Since several languages are case insensitive, there must be no types and members that differ only by case, e.g. MyObject and myObject, and several other features. Thus, if you don't plan to work with other .NET languages there is no reason to mark your code as CLSCompliant.
The only negative effects would be compiler errors when your code is marked as CLSCompliant, but it is not.

What are major differences between C# and Java?

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I just want to clarify one thing. This is not a question on which one is better, that part I leave to someone else to discuss. I don't care about it.
I've been asked this question on my job interview and I thought it might be useful to learn a bit more.
These are the ones I could come up with:
Java is "platform independent". Well nowadays you could say there is the Mono project so C# could be considered too but
I believe it is a bit exaggerating. Why? Well, when a new release of Java is done it is simultaneously available on all platforms it supports, on the other hand how many features of C# 3.0 are still missing in the Mono implementation? Or is it really CLR vs. JRE that we should compare here?
Java doesn't support events and delegates. As far as I know.
In Java all methods are virtual
Development tools: I believe there isn't such a tool yet as Visual Studio. Especially if you've worked with team editions you'll know what I mean.
Please add others you think are relevant.
Update:
Just popped up my mind, Java doesn't have something like custom attributes on classes, methods etc. Or does it?
Comparing Java 7 and C# 3
(Some features of Java 7 aren't mentioned here, but the using statement advantage of all versions of C# over Java 1-6 has been removed.)
Not all of your summary is correct:
In Java methods are virtual by default but you can make them final. (In C# they're sealed by default, but you can make them virtual.)
There are plenty of IDEs for Java, both free (e.g. Eclipse, Netbeans) and commercial (e.g. IntelliJ IDEA)
Beyond that (and what's in your summary already):
Generics are completely different between the two; Java generics are just a compile-time "trick" (but a useful one at that). In C# and .NET generics are maintained at execution time too, and work for value types as well as reference types, keeping the appropriate efficiency (e.g. a List<byte> as a byte[] backing it, rather than an array of boxed bytes.)
C# doesn't have checked exceptions
Java doesn't allow the creation of user-defined value types
Java doesn't have operator and conversion overloading
Java doesn't have iterator blocks for simple implemetation of iterators
Java doesn't have anything like LINQ
Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and lambda expressions. Anonymous inner classes usually fill these roles, but clunkily.
Java doesn't have expression trees
C# doesn't have anonymous inner classes
C# doesn't have Java's inner classes at all, in fact - all nested classes in C# are like Java's static nested classes
Java doesn't have static classes (which don't have any instance constructors, and can't be used for variables, parameters etc)
Java doesn't have any equivalent to the C# 3.0 anonymous types
Java doesn't have implicitly typed local variables
Java doesn't have extension methods
Java doesn't have object and collection initializer expressions
The access modifiers are somewhat different - in Java there's (currently) no direct equivalent of an assembly, so no idea of "internal" visibility; in C# there's no equivalent to the "default" visibility in Java which takes account of namespace (and inheritance)
The order of initialization in Java and C# is subtly different (C# executes variable initializers before the chained call to the base type's constructor)
Java doesn't have properties as part of the language; they're a convention of get/set/is methods
Java doesn't have the equivalent of "unsafe" code
Interop is easier in C# (and .NET in general) than Java's JNI
Java and C# have somewhat different ideas of enums. Java's are much more object-oriented.
Java has no preprocessor directives (#define, #if etc in C#).
Java has no equivalent of C#'s ref and out for passing parameters by reference
Java has no equivalent of partial types
C# interfaces cannot declare fields
Java has no unsigned integer types
Java has no language support for a decimal type. (java.math.BigDecimal provides something like System.Decimal - with differences - but there's no language support)
Java has no equivalent of nullable value types
Boxing in Java uses predefined (but "normal") reference types with particular operations on them. Boxing in C# and .NET is a more transparent affair, with a reference type being created for boxing by the CLR for any value type.
This is not exhaustive, but it covers everything I can think of off-hand.
The following is a great in depth reference by Dare Obasanjo on the differences between C# and Java. I always find myself referring to this article when switching between the two.
http://www.25hoursaday.com/CsharpVsJava.html
C# has automatic properties which are incredibly convenient and they also help to keep your code cleaner, at least when you don't have custom logic in your getters and setters.
Features of C# Absent in Java
• C# includes more primitive types and the functionality to catch arithmetic exceptions.
• 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.
• Event handling is a "first class citizen"—it is part of the language itself.
• Allows the definition of "structs", which are similar to classes but may be allocated on the stack (unlike instances of classes in C# and Java).
• C# implements properties as part of the language syntax.
• C# allows switch statements to operate on strings.
• C# allows anonymous methods providing closure functionality.
• C# allows iterator that employs co-routines via a functional-style yield keyword.
• C# has support for output parameters, aiding in the return of multiple values, a feature shared by C++ and SQL.
• C# has the ability to alias namespaces.
• C# has "Explicit Member Implementation" which allows a class to specifically implement methods of an interface, separate from its own class methods. This allows it also to implement two different interfaces which happen to have a method of the same name. The methods of an interface do not need to be public; they can be made to be accessible only via that interface.
• C# provides integration with COM.
• Following the example of C and C++, C# allows call by reference for primitive and reference types.
Features of Java Absent in C#
• Java's strictfp keyword guarantees that the result of floating point operations remain the same across platforms.
• Java supports checked exceptions for better enforcement of error trapping and handling.
Another good resource is http://www.javacamp.org/javavscsharp/
This site enumerates many examples that ilustrate almost all the differences between these two programming languages.
About the Attributes, Java has Annotations, that work almost the same way.
Generics:
With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T> class the java compiler generates Byte Code as if it was Foo<Object>. This means casting and also boxing/unboxing will have to be done in the "background".
I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.
Please go through the link given below
msdn.microsoft.com/en-us/library/ms836794.aspx
It covers both the similarity and difference between C# and java

Categories