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.
2 | 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!
2 | 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.
9 | throw new ArgumentNullException( "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.
2 | public Person(String name, int age) { |
If it is mandatory to do it in the first line, why not make calling the super constructor part of the language?
2 | public Person( string name, int age) : base (name) { |
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.
1 | public Person( string name) { |
4 | public Person( string name, int age) : this (name) { |
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".
2 | public static final String NAME_PARAMETER = "name" ; |
In C# you have a keyword for constant variables.
2 | 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?
2 | package trifork.example; |
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?
1 | namespace Trifork.Example { |
Using another class
In Java you would write it down like this:
2 | import trifork.example.Person; |
Again this is just a keyword-thing but still, it describes what it does way better in C#.
2 | 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.
1 | string name = "My name" ; |
2 | 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:
2 | if (object1.equals(object2)) { |
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:
2 | if (object1 == null ? object2 == null : object1.equals(object2)) { |
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)
1 | if (object1 == object2) { |
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:
3 | Calendar calendar = Calendar.getInstance(); |
5 | calendar.add(Calendar.HOUR, 2 ); |
6 | 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.
2 | DateTime dateTime = DateTime.Now; |
3 | dateTime = dateTime.AddHours(2); |
Formatting dates as a string
In Java:
2 | DateFormat formatter = new SimpleDateFormat( "dd-MM-yyyy" ); |
3 | String dateString = formatter.format(date); |
C#:
1 | DateTime date = DateTime.Now; |
2 | 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.
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.
2 | (animal as Duck).quack(); |
Threading
Threading is also something that is part of the C# language, using the "await" and "async" keywords.
1 | async Task< int > AccessTheWebAsync() { |
2 | HttpClient client = new HttpClient(); |
8 | string urlContents = await getStringTask; |
9 | 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.
2 | final String name = "My name" ; |
2 | 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:
2 | public String nameForPerson(Person person) { |
3 | return person == null ? null : person.getName(); |
In C# a shorthand notation exists for this type of situation:
2 | public string nameForPerson(Person person) { |
3 | return person ?? person.Name; |
This shorthand notation can also be useful if you're using a singleton-like pattern:
2 | private PersonRepository personRepository; |
4 | public PersonRepository PersonRepository() { |
5 | 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??
1 | Map<String, String> entries = new HashMap<>(); |
2 | entries.put( "a" , "apple" ); |
3 | entries.put( "b" , "banana" ); |
5 | String apple = entries.get( "a" ); |
Anyway, C# has a literal notation for this:
1 | var entries = new Dictionary< string , string > { |
5 | string apple = entries[ "a" ]; |
A similar thing works for lists:
1 | var list = new List< string > { "apple" , "banana" }; |
SQL is part of the language
Search through lists like this:
1 | var results = from p in list |
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:
1 | 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!
1 | 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.
1 | class OutReturnExample { |
2 | public void OutMethod( out int value, out string text) { |
4 | text = "I've been returned" ; |
9 | OutMethod( out value, out text); |
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.
3 | public String toString() { |
2 | public override string ToString() { |
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!
ConversionConversion EmoticonEmoticon