Friday, April 20, 2012

C# envy

I was converting a small Java class to C#, and found a lot to like about it as a language.  For even a simple class - just collection and string manipulation, no frameworks - it seemed like some common tasks were easier, more elegant and less verbose.  Some examples:
  • Object initializers.  It's great to be able to do 'new Foo() { bar = "xxx", baz = "yyy" }' instead of having to call setters individually, or having to make a constructor passing in properties in a specific order.
  • Collection initializers, like "new List<int> {1,2,3}" instead of Arrays.asList
  • "var" keyword.  var foo = new List<int>, as opposed to redundant List<int> x = new ArrayList<int>().
  • Operator overloading, especially "==" for immutable value types like strings and integers.  You don't have to worry about things like "x == y" working if x and y are both ints but not Integers.  
  • Operator overloading for collection indexing.  Where's the "Get" method on a Dictionary?   Don't need one - it's square brackets, just like a Javascript object.
It looks like Java 8 will give us collection initializers but I'm not sure about others.
Post a Comment