At Kalistick we are a Java shop from the beginning: the first version of our product analyzed only Java code. But we are not bigot, we are using and analyzing C# too since 2008. We notice that Java developers generally tend to look scornfully at C#, as a copycat created by Microsoft and used by dummies. In theses blog series, I am going to try to sweep this nonsense and show some of the C# goodness.
- Part 1: Differences in similarities
Java and C# are more alike than they are different: both are curly-bracket languages like C and C++, both are statically, strongly and explicitly typed, both are class-based object-oriented, both are designed with runtime compilation in mind and both use garbage-collection.
In this post, I will focus on differences about common features that they share.
Unified type system
In Java the primitive types (byte, int, bool, float, char…) are special, they are not object-oriented and do not share a common ancestor with reference types. But they do have class type wrappers, that can be used to represent them and plug them in the Object hierarchy (i.e. Integer for int). This choice was made to improve performance.
On the contrary, C# has a unified type system in which all types derive from a common root type: System.Object, even the primitive types. So all types implement the Object methods (ToString, Equal, GetHashCode…), and you can do things like 3.ToString(). Mixed with extension methods this could provide nice dsl-like syntax :
TimeSpan workingTime = 7.Hours() + 30.Minutes();
The beauty is that value types are just as efficient as Java primitives, as long as the developer use them as values. Only if he tries to treat them as objects do they become heap allocated, through boxing/unboxing.
Explicit virtual methods
In Java all methods are virtual by default (although they can be sealed by using the final modifier to disallow overriding) while in C# they are not. To make a method virtual in C#, the programmer must explicitly declare it virtual using the virtual keyword.
There are several reasons for this choice, the first one is performance: there is a performance overhead associated with virtual methods as they cannot be inlined normally and require an indirect call via the vtable. (Sun JVM implementation implements inlining of the most commonly called virtual methods). The second and more important issue is versioning: C# is designed so that versioning between base and derived classes in different libraries can evolve and maintain backward compatibility. For example, the introduction of a new member in a base class with the same name as a member in a derived class is completely supported by C# and does not lead to unexpected behavior. The last one is readability: the developer intent is clearly stated. In Java, if the Override annotation is not used you never know if the developer intent was to override the method or not.
class Meme
{
public virtual void Spread() {}
}
class ThreeHundred : Meme
{
public override void Spread()
{
Console.Write("This is sparta!");
}
}
class Dbz: Meme
{
// Not a method override
public void Spread()
{
Console.Write("It's over nine thousaaannnd!");
}
}
True Generic
Regarding generics, Java and C# show a syntactical similarity, but when you look under the hood they have deep differences.
Java generics are implemented in the compiler only; the runtime has no knowledge of the generic type system. Instead, a process called type erasure transforms generics classes and methods during compilation: all generic types are replaced by their raw version and casts and checks are inserted in client code. The resulting byte code will contain no references to any generic types or parameters. Java generics are a syntactic sugar, they don’t get you any of the execution efficiency.
C# generics are not a language feature only, they are implemented in the CLR (Common Language Runtime, equivalent to the JVM) as well. During compilation, generics are verified for correctness, but the generation of the implementation is deferred to class-load time. Code invoking generics are fully compiled and can safely assume generics to be type-safe. This is called reification. Unlike with Java, there is no need to inject casts or type-checks. Generic types and methods can be constructed with both reference (classes, delegates, interfaces…) and value types (primitive type, struct, enum…)
The benefits of C# implementation are performance improvement (no cast and no boxing/unboxing of value types), deep type safety verification and reflection capability.
public void AwesomeGenericMethod<T>(T t) where T : new()
{
T newInstance = new T (); // Causes a type creation error in Java
T[] array = new T [0]; // Causes generic array creation error in Java
T defaultValue = default(T);
Type type = typeof(T);
List<T> list = new List<T> ();
}
// Generic with same name but a different number of generic type
public void AwesomeGenericMethod<T,U>(T t, U u) where T : new()
{
}
Mark Reinhold (Chief Architect of Java Platform Group at Oracle) talked about reification at Devoxx 2011. But this feature is still not planned for next major releases of Java.
Farewell checked exceptions
Exceptions in Java and C# fairly work the same way, there is only one major difference between the two: Java contains the notion of checked exceptions. In Java you can declare throws ExceptionType in the method declaration, this forces any callers of that method to handle the exception. This is a great idea on paper but in practice it tends to be an annoyance more than anything, bringing new issues:
- Versioning: adding a new checked exception to a method declaration in a new version breaks client code; it’s like adding a method to an interface. In version one you create a method
foothat declares it throws exceptions A and B, in version two you add a bunch of features and throw exception D, this is a breaking change because existing callers do not handle this exception. - Scalability: in large application with a lot of dependencies, the number of exception grows exponentially and people will often shunt the feature by throwing the generic Exception or use empty catch block.
The idea behind checked exceptions is great but they tend to intrude to much, specially in big application. That’s why there is no checked exception in C# or any other mainstream languages: it’s up to the developer to handle them.
Double rainbow accessors
Java uses naming convention for its accessors and modifiers (i.e. getAddress, setAddress, isValid…). In C#, accessors and modifiers are built-in; with properties no need to write getters and setters, everything looks like a direct field access, even if it isn’t. (many languages uses the same idiom, by the way)
class Meme
{
// A private backing field is created by the compiler
public string CatchPhrase { get; set;}
public string URL { get; set;}
}
Meme meme = new Meme();
meme.CatchPhrase = "Rick roll'd";
meme.URL = "http://www.youtube.com/watch?v=EK2tWVj6lXw";
// Equivalent in Java
class Meme
{
private String catchPhrase;
private String url;
public String getCatchPhrase()
{
return catchPhrase;
}
public void setCatchPhrase(String catchPhrase)
{
this.catchPhrase = catchPhrase;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
}
When you declare a property as an auto-implemented one, the compiler creates a private, anonymous backing field that can only be accessed through the property’s get and set accessors. It brings consistency: the field is always used via the accessors even within the class and it looks cleaner and shorter!
A special kind of accessors exist that doesn’t exist in Java: the indexer; it is like a get/set with a parameter. C# collection like Dictionary (equivalent to Java Map) use indexer :
var keywordsMapping = new Dictionary<string, string>();
keywordsMapping["super"] = "base";
keywordsMapping["boolean"] = "bool";
Console.Write("Java => C# : {0} => {1}", "super", keywordsMapping["super"]);
You Say I’m Crazy, I got Your Crazy! You’re nothing but an Initializer!
You often has to create an object and initialize it right after, this can be done with constructor if one is available. Otherwise you has to create the object and then call the different setters.
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
Meme leeroy = new Meme {
CatchPhrase = "Leeroy Jenkins",
URL = "http://www.youtube.com/watch?v=LkCNJRfSZBU"
};
It works with collection too:
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Dictionary<string, string> keywordsMapping = new Dictionary<string, string>() {
{"super", "base"},
{"boolean", "bool"},
{"import", "using"}
};
Verbatim string
Escaping characters in string literal is a real pain, it clutters the string meaning, especially with Regex! In C# verbatim string allows backslashes, tabs, quotes and newlines to be part of a string without using escape sequences.
string pattern = @"\d{3}-\d{3}-\d{4}";
string input = @"Multiline string
325-532-4521";
Regex.IsMatch(input, pattern, RegexOptions.Multiline);
It’s a wrap
In this post I have showed that despite its similarity with Java, C# is meant to make developers life easier, to ease their burden (and these are only samples among others). Not too bad for a copycat!
Java developers have brought responses to these lacks in their favorite language by introducing new scripting languages on top of the JVM. For instance, Groovy has most of features presented here. But Java language still does not change!
In the following post I am going to describe the totally different features that bring C# to another level of expressiveness and effectiveness: lamda expression, LINQ, dynamic, extension methods...

![CropperCapture[45]](http://blog.kalistick.com/wp-content/uploads/2011/03/CropperCapture45-600x251.png)
Pingback: Java vs C# « the don blog
Pingback: links for 2011-05-23 « pabloidz
Pingback: Feeds Of The Week #2 « kerrubin's blog
Pingback: Дайджест недели, 27 мая | Софт Буум
Pingback: Why Java folks should stop looking down on C# [2/4] A brand new world
Pingback: Why Java folks should look forward to Scala | /var/log/mind
Pingback: Why Java folks should stop looking down on C# [3/4] The ecosystem
Pingback: ASP.NET , PHP , WEB DESIGN | Размисли