Windows Phone 8 - C# vs. Java

csharp-vs-java it is now time to take a look at the programming language: C# or "C sharp". I want to focus purely on the language itself and compare it to the language I know best: Java. I was surprised how good C# was compared to Java. The syntax of both languages look a lot alike. I want to highlight some of the language features I discovered while writing my first app of which I thought: wow, I wish Java would have this!

Getters and setters

Getters and setters appear to be part of the language.
1class Person {
2    public int Age { get; set; }
3}
Do you want the getter to be public and the setter only accessible from within the class (private)? No problem!
1class Person {
2    public int Age { get; private set; }
3}
As you can see, this is way shorter than implementing a default getter and/or setter in Java. Note that in C#, public properties and methods start with a capital letter. This is unlike Java, where those types of symbols start with a lower case letter.
If you decide to have custom logic (which is hardly ever the case) in your getter or setter you can still do so.
1class Person {
2    private int age;
3    public int Age {
4        get {
5            return age;
6        }
7        set {
8            if (value == null) {
9                throw new ArgumentNullException("value");
10            }
11            age = value;
12        }
13    }
14}

Calling constructors of the super class

When you create a subclass you often want it to have constructors that call the constructor of the superclass. In Java, there is a foggy compiler-rule that says you can only call the super-constructor in the first line of code in the constructor of your subclass.
1// Java
2public Person(String name, int age) {
3    super(name);
4    this.age = age;
5}
If it is mandatory to do it in the first line, why not make calling the super constructor part of the language?
1// C#
2public Person(string name, int age) : base(name) {
3    this.age = age;
4}
I like this way of calling the super (base) constructor a lot better. The same applies for when you want to call another constructor in the same class.
1public Person(string name) {
2    this.name = name;
3}
4public Person(string name, int age) : this(name) {
5    this.age = age;
6}

Constants

If you want to define a constant variable you want it to be static, and you want it to be immutable. In Java you have to literally write those two things down as "static" and "final".
1// Java
2public static final String NAME_PARAMETER = "name";
In C# you have a keyword for constant variables.
1// C#
2public const string NameParameter = "name";
It does the same thing but is more declarative and shorter. It isn't a big language feature but hey, every little helps!

Packages

This is more like a different keyword than a new language feature. I want to highlight it because I like the syntax better in C#. If you write a class definition, you do it using curly brackets around the definition. Why doesn't it work the same for package?
1// Java
2package trifork.example;
3public class Person {
4}
Why is package a statement of its own? Use curly brackets! And is "package" the right word for what it is? Sure, it IS a package, but what does it do? That's right, it provides a namespace for your classes. So why not call it like what it is as C# does?
1namespace Trifork.Example {
2    public class Person {
3    }
4}

Using another class

In Java you would write it down like this:
1// Java
2import trifork.example.Person;
Again this is just a keyword-thing but still, it describes what it does way better in C#.
1// C#
2using Trifork.Example.Person;
"Importing" a class is what we did using C, where the compiler would literally import (copy) the contents of the header-file of one class into the header file of another class. In both Java and C# this is no longer the case. So why does Java still call it "import"? Because it is familiar to C-programmers? Isn't using a better keyword for it?

String and Object are part of the language

In Java the String and Object types feel a bit like an after thought. It feels like something they added to the SDK later on when the language itself was already finished. In C# those two types are integrated into the language and therefore are keywords instead of classes.
1string name = "My name";
2object person = new Person(name);

Equality

Why do we have to use equals() when comparing two Java objects? Because if we would use the == operator, it would only resolve as true when both references are referring the exact same instance. Say we're comparing object1 and object2:
1// Java
2if (object1.equals(object2)) {
3    // Do your thing
4}
What if both object1 and object2 can be null at some point, you even risk the program throwing a NullPointerException so you would have to write it down like this:
1// Java
2if (object1 == null ? object2 == null : object1.equals(object2)) {
3    // Do your thing
4}
In C# another thing that is part of the language is object equality. You can safely use the == operator on objects, because at runtime, the Equals() method will be called. (only when object1 is not null of course)
1if (object1 == object2) {
2    // Do your thing
3}
One side note: in C# it is possible override the behaviour of the == operator so the behaviour could change in theory.

Better date/time API

We all know the date/time API in Java sucks, that's why many of us are using Joda Time instead. But without Joda Time you would have to write this kind of code in Java:
1// Java
2Date date = new Date();
3Calendar calendar = Calendar.getInstance();
4calendar.setTime(date);
5calendar.add(Calendar.HOUR, 2);
6date = calendar.getTime();
Besides the fact that this is a lot of code for something simple, it is weird that an object called "Date" also contains the time. In C# the standard date/time API already works kind of like Joda Time does.
1// C#
2DateTime dateTime = DateTime.Now;
3dateTime = dateTime.AddHours(2);

Formatting dates as a string

In Java:
1Date date = new Date();
2DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
3String dateString = formatter.format(date);
C#:
1DateTime date = DateTime.Now;
2string dateString = date.ToString("dd-MM-yyyy");
Do I even need to explain this one?

Casting a class

Casting a class to another class can be done the same way in Java as in C#. Sometimes you want to do in-line casting to a class to be able to call one single method on it.
1// Java & C#
2((Duck)animal).quack();
In C# an alternative way exists to cast a class, with the "as" keyword, which makes in-line casting a class a little more readable.
1// C#
2(animal as Duck).quack();

Threading

Threading is also something that is part of the C# language, using the "await" and "async" keywords.
1async Task<int> AccessTheWebAsync() {
2    HttpClient client = new HttpClient();
3    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
4 
5    // You can do work here that doesn't rely on the string from GetStringAsync.
6    DoIndependentWork();
7 
8    string urlContents = await getStringTask;
9    return urlContents.Length;
10}
If you define a method as being "async", the method will automatically be executed in the background and will return a "Task" instance immediately, which is similar to a "Future" object in Java. The calling code can "await" the result and do some independent work first.

Readonly fields

C# uses the "readonly" keyword instead of "final" in Java. Not a new feature, but again a better word for what it does.
1// Java
2final String name = "My name";
1// C#
2readonly string name = "My name";

"??" notation

Have you ever run into a situation that requires your code to return something, only if a certain variable is not null, and null if it is? You would write code like this:
1// Java
2public String nameForPerson(Person person) {
3    return person == null ? null : person.getName();
4}
In C# a shorthand notation exists for this type of situation:
1// C#
2public string nameForPerson(Person person) {
3    return person ?? person.Name;
4}
This shorthand notation can also be useful if you're using a singleton-like pattern:
1// C#
2private PersonRepository personRepository;
3 
4public PersonRepository PersonRepository() {
5    return personRepository ?? (personRepository = new PersonRepository());
6}

Literal notation for maps and arrays

Even the inferior Objective C language has a literal notation for arrays (lists) and dictionaries (maps), so why doesn't Java have it??
1Map<String, String> entries = new HashMap<>();
2entries.put("a", "apple");
3entries.put("b", "banana");
4 
5String apple = entries.get("a");
Anyway, C# has a literal notation for this:
1var entries = new Dictionary<string, string> {
2    { "a", "apple" },
3    { "b", "banana" }
4};
5string apple = entries["a"];
A similar thing works for lists:
1var list = new List<string> { "apple", "banana" };
2string apple = list[0];

SQL is part of the language

Search through lists like this:
1var results = from p in list
2            where p.Age > 18
3            select p;
This will give you all Person objects in the "list" where the age is more than 18. You can also do similar things using LINQ and lambda expressions:
1var results = list.Where(person => person.Age > 18);
Instead of searching for specific people, you want a list of all names of those people? No problem!
1var names = list.Select(person => perons.Name);

Using pointers

Many people get goose bumps when they hear the word "pointer" because they know what a mess you can make of your code when you have to use pointers directly. In C# you of course mainly use references, just like in Java. But sometimes pointers can be very handy. What if you create a method and you would like to return multiple values? In Java I always create a new class containing each value as a field, and instantiate that class and use it to return mulitple values. In C# you can simply use the "out" keyword that works like a pointer.
1class OutReturnExample {
2    public void OutMethod(out int value, out string text) {
3        value = 44;
4        text = "I've been returned";
5    }
6    public void DoIt() {
7        int value;
8        string text;
9        OutMethod(out value, out text);
10        // value is now 44
11        // text is now "I've been returned"
12    }
13}

Overriding methods

And finally, not a new feature, but again something that is part of the language where in Java it isn't, which makes it nicer.
1// Java
2@Override
3public String toString() {
4    return "description";
5}
1// C#
2public override string ToString() {
3    return "description";
4}

Probably many more features

C# probably has many more features I did not discover in the short time I have worked with it so far but I am eager to discover them!
Previous
Next Post »