Trifork Blog

Axon Framework, DDD, Microservices

Windows Phone 8 – C# vs. Java

September 17th, 2013 by
|

csharp-vs-java
Welcome back to another brand new Windows Phone 8 blog! After I explored the UI and checked out the IDE 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.

class Person {
    public int Age { get; set; }
}

Do you want the getter to be public and the setter only accessible from within the class (private)? No problem!

class Person {
    public int Age { get; private set; }
}

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.

class Person {
    private int age;
    public int Age {
        get {
            return age;
        }
        set {
            if (value == null) {
                throw new ArgumentNullException("value");
            }
            age = value;
        }
    }
}

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.

// Java
public Person(String name, int age) {
    super(name);
    this.age = age;
}

If it is mandatory to do it in the first line, why not make calling the super constructor part of the language?

// C#
public Person(string name, int age) : base(name) {
    this.age = age;
}

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.

public Person(string name) {
    this.name = name;
}
public Person(string name, int age) : this(name) {
    this.age = age;
}

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”.

// Java
public static final String NAME_PARAMETER = "name";

In C# you have a keyword for constant variables.

// C#
public 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?

// Java
package trifork.example;
public class Person {
}

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?

namespace Trifork.Example {
    public class Person {
    }
}

Using another class

In Java you would write it down like this:

// Java
import trifork.example.Person;

Again this is just a keyword-thing but still, it describes what it does way better in C#.

// C#
using 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.

string name = "My name";
object 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:

// Java
if (object1.equals(object2)) {
    // Do your thing
}

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:

// Java
if (object1 == null ? object2 == null : object1.equals(object2)) {
    // Do your thing
}

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)

if (object1 == object2) {
    // Do your thing
}

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:

// Java
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, 2);
date = 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.

// C#
DateTime dateTime = DateTime.Now;
dateTime = dateTime.AddHours(2);

Formatting dates as a string

In Java:

Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String dateString = formatter.format(date);

C#:

DateTime date = DateTime.Now;
string 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.

// Java & C#
((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.

// C#
(animal as Duck).quack();

Threading

Threading is also something that is part of the C# language, using the “await” and “async” keywords.

async Task<int> AccessTheWebAsync() {
    HttpClient client = new HttpClient();
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    string urlContents = await getStringTask;
    return urlContents.Length;
}

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.

// Java
final String name = "My name";
// C#
readonly 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:

// Java
public String nameForPerson(Person person) {
    return person == null ? null : person.getName();
}

In C# a shorthand notation exists for this type of situation:

// C#
public string nameForPerson(Person person) {
    return person ?? person.Name;
}

This shorthand notation can also be useful if you’re using a singleton-like pattern:

// C#
private PersonRepository personRepository;

public PersonRepository PersonRepository() {
    return personRepository ?? (personRepository = new PersonRepository());
}

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??

Map<String, String> entries = new HashMap<>();
entries.put("a", "apple");
entries.put("b", "banana");

String apple = entries.get("a");

Anyway, C# has a literal notation for this:

var entries = new Dictionary<string, string> {
    { "a", "apple" },
    { "b", "banana" }
};
string apple = entries["a"];

A similar thing works for lists:

var list = new List<string> { "apple", "banana" };
string apple = list[0];

SQL is part of the language

Search through lists like this:

var results = from p in list
            where p.Age > 18
            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:

var 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!

var 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.

class OutReturnExample {
    public void OutMethod(out int value, out string text) {
        value = 44;
        text = "I've been returned";
    }
    public void DoIt() {
        int value;
        string text;
        OutMethod(out value, out text);
        // value is now 44
        // text is now "I've been returned"
    }
}

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.

// Java
@Override
public String toString() {
    return "description";
}
// C#
public override string ToString() {
    return "description";
}

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!

Conclusion

Because the Visual Studio IDE is really crappy without a third party tool called Resharper (see my previous blog), I was expecting a language just as crappy. But it turned out it is quite the opposite! The language C# by itself is a really thought out language with many more features than Java, while it shares a lot of the same syntax as Java. Therefore the learning curve for this language is very steep when you already know Java (or not steep, depending on how you interpret “learning curve”, to clarify: I mean easy to learn). So writing code by combining Resharper and C# turned out to be a great joy and makes the entire Windows Phone 8 platform very worthwhile.

2 Responses

  1. October 7, 2013 at 05:05 by Taylor Brazelton

    This article was very in-depth and shows a lot of similarities between C# and Java.

    This really helps when I am trying to show my friends why I enjoy C# better than writing Java any day.

  2. May 4, 2014 at 11:40 by Hung Nguyen

    Great article ! I’m forever a big fan of C#. C# is so far beautiful and productivity but especially more powerful once the upcoming .NET Native Compiler is officially released !